look at this: https://developer.mozilla.org/en-US/docs/Web/API/event.keyCode
In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g. 'a'), charCode is set to the code of that character, respecting the letter case. (i.e. charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode. keyCode is always set in the keydown and keyup events. In these cases, charCode is never set. To get the code of the key regardless of whether it was stored in keyCode or charCode, query the which property. Characters entered through an IME do not register through keyCode or charCode.
I was getting this error because my local branchname did not match the new remote branch I was trying to create with git push origin <<branchname>>
.
If you just want the list, then you should ask here: http://unix.stackexchange.com
The answer is: cd / && find -name *.js
If you want to implement this, you have to specify the language.
To call the function you have to add ()
{this.renderIcon()}
In the controller, shouldn't the response body annotation be on the return type and not the method, like so :
@RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)
public @ResponseBody Weather getTemparature(@PathVariable("id") Integer id){
Weather weather = weatherService.getCurrentWeather(id);
return weather;
}
I'd also use the raw jquery.ajax function, and make sure contentType and dataType are being set correctly.
On a different note, I find the spring handling of json rather problematic. It was easier when I did it all myself using strings, and GSON.
Use:
function Which([string] $cmd) {
$path = (($Env:Path).Split(";") | Select -uniq | Where { $_.Length } | Where { Test-Path $_ } | Get-ChildItem -filter $cmd).FullName
if ($path) { $path.ToString() }
}
# Check if Chocolatey is installed
if (Which('cinst.bat')) {
Write-Host "yes"
} else {
Write-Host "no"
}
Or this version, calling the original where command.
This version also works better, because it is not limited to bat files:
function which([string] $cmd) {
$where = iex $(Join-Path $env:SystemRoot "System32\where.exe $cmd 2>&1")
$first = $($where -split '[\r\n]')
if ($first.getType().BaseType.Name -eq 'Array') {
$first = $first[0]
}
if (Test-Path $first) {
$first
}
}
# Check if Curl is installed
if (which('curl')) {
echo 'yes'
} else {
echo 'no'
}
You need $route defined in your module and change the JS to this.
$scope.backLinkClick = function () {
window.location.reload();
};
that works fine for me.
I made a really dumb mistake and forgot to define name
attributes for inputs in my html file.
So instead of
<input type="password" class="form-control" id="password">
I have this.
<input type="password" class="form-control" id="password" name="password">
Now request.body
is populated like this: { password: 'hhiiii' }
View.GONE = The view will not show and the rest of the views will not take its existence into consideration
View.INVISIBLE = The view will not show, but it will take its assigned space in the layout
Durgesh's approach does work.
I also used such KVC solutions many times. Despite it seems to be undocumented, but it works. Frankly, you don't use any private methods here - only Key-Value Coding which is legal.
P.S. Yesterday my new app appeared at AppStore without any problems with this approach. And it is not the first case when I use KVC in changing some read-only properties (like navigatonBar) or private ivars.
This works fine for me. It allows value to be entered even after focus changed and retrieved back. For example: 123.00
, 12.12
, 0.01
, etc..
1.Integer.parseInt(getString(R.string.valuelength))
Specifies the length of the input digits.Values
accessed from string.xml
file.It is quiet easy to change values.
2.Integer.parseInt(getString(R.string.valuedecimal))
, this is for decimal places max limit.
private InputFilter[] valDecimalPlaces;
private ArrayList<EditText> edittextArray;
valDecimalPlaces = new InputFilter[] { new DecimalDigitsInputFilterNew(
Integer.parseInt(getString(R.string.valuelength)),
Integer.parseInt(getString(R.string.valuedecimal)))
};
Array of EditText
values that allows to perform action.
for (EditText etDecimalPlace : edittextArray) {
etDecimalPlace.setFilters(valDecimalPlaces);
I just used array of values that contain multiple edittext
Next DecimalDigitsInputFilterNew.class
file.
import android.text.InputFilter;
import android.text.Spanned;
public class DecimalDigitsInputFilterNew implements InputFilter {
private final int decimalDigits;
private final int before;
public DecimalDigitsInputFilterNew(int before ,int decimalDigits) {
this.decimalDigits = decimalDigits;
this.before = before;
}
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches("(([0-9]{1})([0-9]{0,"+(before-1)+"})?)?(\\.[0-9]{0,"+decimalDigits+"})?")) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
}
Something that has worked for me in the past was to determine the offset (in milliseconds) between the user's timezone and GMT. Once you have the offset, you can simply add/subtract (depending on which way the conversion is going) to get the appropriate time in either timezone. I would usually accomplish this by setting the milliseconds field of a Calendar object, but I'm sure you could easily apply it to a timestamp object. Here's the code I use to get the offset
int offset = TimeZone.getTimeZone(timezoneId).getRawOffset();
timezoneId is the id of the user's timezone (such as EST).
There are actually two ways to add a favicon to a website.
<link rel="icon">
Simply add the following code to the <head>
element:
<link rel="icon" href="http://example.com/favicon.png">
PNG favicons are supported by most browsers, except IE <= 10. For backwards compatibility, you can use ICO favicons.
Note that you don't have to precede icon
in rel
attribute with shortcut
anymore. From MDN Link types:
The
shortcut
link type is often seen beforeicon
, but this link type is non-conforming, ignored and web authors must not use it anymore.
favicon.ico
in the root directoryFrom another SO answer (by @mercator):
All modern browsers (tested with Chrome 4, Firefox 3.5, IE8, Opera 10 and Safari 4) will always request a
favicon.ico
unless you've specified a shortcut icon via<link>
.
So all you have to do is to make the /favicon.ico
request to your website return your favicon. This option unfortunately doesn't allow you to use a PNG icon.
See also favicon.png vs favicon.ico - why should I use PNG instead of ICO?
You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.
Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)
follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html
replot
This is another way to get multiple plots at once:
plot file1.data
replot file2.data
A more modern approach using Promise and async/await :
toDataURL(url) {
return fetch(url).then((response) => {
return response.blob();
}).then(blob => {
return URL.createObjectURL(blob);
});
}
then
async download() {
const a = document.createElement("a");
a.href = await toDataURL("https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png");
a.download = "myImage.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
Find documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Simple solution:
document.getElementById("upload-files").value = "";
<?php
$table = 'orders';
$query = "SHOW COLUMNS FROM $table";
if($output = mysql_query($query)):
$columns = array();
while($result = mysql_fetch_assoc($output)):
$columns[] = $result['Field'];
endwhile;
endif;
echo '<pre>';
print_r($columns);
echo '</pre>';
?>
In VS 2017, i have checked SQL Server Data Tools during the installation and it doesn't help. So I have downloaded and installed Microsoft.RdlcDesigner.vsix
Now it works.
UPDATE
Another way is to use Extensions and Updates.
Go to Tools > Extensions and Updates choose Online then search for Microsoft Rdlc Report Designer for Visual studio and click Download. It need to close VS to start installation. After installation you will be able to use rdlc designer.
Hope this helps!
Adding a solution that doesn't use WinForms but NativeMethods instead. First you need to define the native methods needed.
public static class NativeMethods
{
public const Int32 MONITOR_DEFAULTTOPRIMERTY = 0x00000001;
public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;
[DllImport( "user32.dll" )]
public static extern IntPtr MonitorFromWindow( IntPtr handle, Int32 flags );
[DllImport( "user32.dll" )]
public static extern Boolean GetMonitorInfo( IntPtr hMonitor, NativeMonitorInfo lpmi );
[Serializable, StructLayout( LayoutKind.Sequential )]
public struct NativeRectangle
{
public Int32 Left;
public Int32 Top;
public Int32 Right;
public Int32 Bottom;
public NativeRectangle( Int32 left, Int32 top, Int32 right, Int32 bottom )
{
this.Left = left;
this.Top = top;
this.Right = right;
this.Bottom = bottom;
}
}
[StructLayout( LayoutKind.Sequential, CharSet = CharSet.Auto )]
public sealed class NativeMonitorInfo
{
public Int32 Size = Marshal.SizeOf( typeof( NativeMonitorInfo ) );
public NativeRectangle Monitor;
public NativeRectangle Work;
public Int32 Flags;
}
}
And then get the monitor handle and the monitor info like this.
var hwnd = new WindowInteropHelper( this ).EnsureHandle();
var monitor = NativeMethods.MonitorFromWindow( hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST );
if ( monitor != IntPtr.Zero )
{
var monitorInfo = new NativeMonitorInfo();
NativeMethods.GetMonitorInfo( monitor, monitorInfo );
var left = monitorInfo.Monitor.Left;
var top = monitorInfo.Monitor.Top;
var width = ( monitorInfo.Monitor.Right - monitorInfo.Monitor.Left );
var height = ( monitorInfo.Monitor.Bottom - monitorInfo.Monitor.Top );
}
I got around this by finding the nuget.exe and moving to an easy to type path (c:\nuget\nuget) and then calling the nuget with this path. This seems to solve the problem. c:\nuget\nuget at the package manager console works as expected. I tried to find the path that the console was using and changing the environment path but was never able to get it to work in that way.
The only three literal characters which are treated specially in the replace clause are /
(to close the clause), \
(to escape characters, backreference, &c.), and &
(to include the match in the replacement). Therefore, all you need to do is escape those three characters:
sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"
Example:
$ export REPLACE="'\"|\\/><&!"
$ echo fooKEYWORDbar | sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"
foo'"|\/><&!bar
Steps to start a certain local MongoDB instance and to connect to in from NodeJS app:
Create mongod.cfg
for a new database using the path C:\Program Files\MongoDB\Server\4.0\mongod.cfg
with the content
systemLog:
destination: file
path: C:\Program Files\MongoDB\Server\4.0\log\mongod.log
storage:
dbPath: C:\Program Files\MongoDB\Server\4.0\data\db
Install mongoDB database by running
mongod.exe --config "C:\Program Files\MongoDB\Server\4.0\mongod.cfg" --install
Run a particular mongoDB database
mongod.exe --config "C:\Program Files\MongoDB\Server\4.0\mongod.cfg"
Run mongoDB service
mongo 127.0.0.1:27017/db
and !see mongoDB actual connection string to coonect to the service from NodeJS app
MongoDB shell version v4.0.9
connecting to: mongodb://127.0.0.1:27017/db?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("c7ed5ab4-c64e-4bb8-aad0-ab4736406c03") }
MongoDB server version: 4.0.9
Server has startup warnings:
...
System.Windows.MessageBox.Show("Hello world"); //WPF
System.Windows.Forms.MessageBox.Show("Hello world"); //WinForms
Sounds like a job for sed
:
sed -n '8,12p' yourfile
...will send lines 8 through 12 of yourfile
to standard out.
If you want to prepend the line number, you may wish to use cat -n
first:
cat -n yourfile | sed -n '8,12p'
This is all because you are not in the desired directory. You need to first get into the desired directory. Mine was angular-phonecat directory. So I typed in cd angular-phonecat
and then npm install
.
In my case, the Windows Firewall
was blocking Android Studio (i.e. java.exe
from Android Studio's jre/bin
folder) from connecting to sites and downloading data. After Windows asked me if I wanted to allow the app through the firewall, I had to do a manual sync File -> Sync project with gradle files
. After that, things were still disfunctional, a manual download of an SDK version 28 was necessary from Tools -> SDK Manager
.
I know I'm posting late but thought it would help at least a few folks!
Both the examples mentioned by tim and defuz(which are top voted) works perfectly fine. However, there is a minute difference which could be significant at times.
Pymongo provides json_util - you can use that one instead to handle BSON types
Output: { "_id": { "$oid": "abc123" } }
Output: { "_id": "abc123" }
Even though, the first method looks simple, both the method need very minimal effort.
for JPA 2+ this does the trick
<jar-file></jar-file>
scan all jars in war for annotated @Entity classes
If you want to modify the file in place, you could always use the original ed
instead of its streaming successor sed
:
ed "$FILE" <<<$'1d\nwq\n'
The ed
command was the original UNIX text editor, before there were even full-screen terminals, much less graphical workstations. The ex
editor, best known as what you're using when typing at the colon prompt in vi
, is an extended version of ed
, so many of the same commands work. While ed
is meant to be used interactively, it can also be used in batch mode by sending a string of commands to it, which is what this solution does.
The sequence <<<$'1d\nwq\n'
takes advantage of Bash's support for here-strings (<<<
) and POSIX quotes ($'
...'
) to feed input to the ed
command consisting of two lines: 1d
, which deletes line 1, and then wq
, which writes the file back out to disk and then quits the editing session.
Here is a first try that's easy on the coder but hard on the CPU which prepends a random number to each line, sorts them and then strips the random number from each line. In effect, the lines are sorted randomly:
cat myfile | awk 'BEGIN{srand();}{print rand()"\t"$0}' | sort -k1 -n | cut -f2- > myfile.shuffled
I ended up here when searching for ”rxjs download file using post”.
This was my final product. It uses the file name and type given in the server response.
import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';
downloadPost(url: string, data: any) {
return ajax({
url: url,
method: 'POST',
responseType: 'blob',
body: data,
headers: {
'Content-Type': 'application/json',
'Accept': 'text/plain, */*',
'Cache-Control': 'no-cache',
}
}).pipe(
map(handleDownloadSuccess),
);
}
handleDownloadSuccess(response: AjaxResponse) {
const downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(response.response);
const disposition = response.xhr.getResponseHeader('Content-Disposition');
if (disposition) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
const filename = matches[1].replace(/['"]/g, '');
downloadLink.setAttribute('download', filename);
}
}
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
/register-form.html
to signup-form.html
./register.php
, then now load (GET) /success.html
./register.php
, then this tells it to redo the POST at /signup.php
.RFC 7231 (from 2014) is very readable and not overly verbose. If you want to know the exact answer, it's a recommended read. Some other answers use RFC 2616 from 1999, but nothing changed.
RFC 7238 specifies the 308 status. It is considered experimental, but it was already supported by all major browsers in 2016.
by typing yes it wont charge taxes, by typing no it will charge taxes.
=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))
Some shortcut is to create a NumberFormatInfo class, set its NumberDecimalSeparator property to "." and use the class as parameter to ToString() method whenever u need it.
using System.Globalization;
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
value.ToString(nfi);
Your selector for the .show()
and .hide()
are not pointing to anything in the code.
Hi Please find the answer below.this is done by validating the date newly created
var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
|| d.getMonth() != (month - 1)
|| d.getDate() != date) {
alert("invalid date");
return false;
}
You can make it even simplier, if you want to avoid extra structures.
service:
mappings:
key1: value1
key2: value2
@Configuration
@EnableConfigurationProperties
public class ServiceConfigurationProperties {
@Bean
@ConfigurationProperties(prefix = "service.mappings")
public Map<String, String> serviceMappings() {
return new HashMap<>();
}
}
And then use it as usual, for example with a constructor:
public class Foo {
private final Map<String, String> serviceMappings;
public Foo(Map<String, String> serviceMappings) {
this.serviceMappings = serviceMappings;
}
}
Map
is internally made up of Map.Entry
objects. Each Entry
contains key
and value
. To get key and value from the entry you use accessor and modifier methods.
If you want to get values
with given key
, use get()
method and to insert value, use put()
method.
#Define and initialize map;
Map map = new HashMap();
map.put("USA",1)
map.put("Japan",3)
map.put("China",2)
map.put("India",5)
map.put("Germany",4)
map.get("Germany") // returns 4
If you want to get the set of keys from map, you can use keySet()
method
Set keys = map.keySet();
System.out.println("All keys are: " + keys);
// To get all key: value
for(String key: keys){
System.out.println(key + ": " + map.get(key));
}
Generally, To get all keys and values from the map, you have to follow the sequence in the following order:
Hashmap
to MapSet
to get set of entries in Map
with entryset()
method.:Set st = map.entrySet();
Iterator it = st.iterator();
Map.Entry
from the iterator: Map.Entry entry = it.next();
getKey()
and getValue()
methods of the Map.Entry
to get keys and values.// Now access it
Set st = (Set) map.entrySet();
Iterator it = st.iterator();
while(it.hasNext()){
Map.Entry entry = mapIterator.next();
System.out.print(entry.getKey() + " : " + entry.getValue());
}
In short, use iterator directly in for
for(Map.Entry entry:map.entrySet()){
System.out.print(entry.getKey() + " : " + entry.getValue());
}
I see that the question is an old one. If anyone stumbles upon this in the future, I think this is one simple way of doing it. Keep the properties file in your project folder.
FileReader reader = new FileReader("Config.properties");
Properties prop = new Properties();
prop.load(reader);
For anyone looking to do this dynamically then setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)
on the buttons object will assist.
Sample
Button search = (Button) findViewById(R.id.yoursearchbutton);
search.setCompoundDrawables('your_drawable',null,null,null);
I had the following error message Port 80 in use by "Unable to open process" with PID 4! Apache WILL NOT start without the configured ports free! You need to uninstall/disable/reconfigure the blocking application or reconfigure Apache and the Control Panel to listen on a different port Starting Check-Timer Control Panel Ready
opened the httpd.conf and changed the listen port from 80 to 1234 in both places
Listen 1234
Then go to Config for the xampp control panel and go to service and port setting and changed the port from 80 to 1234
That worked.
The problem is that POST method is forbidden for Nginx server's static files requests. Here is the workaround:
# Pass 405 as 200 for requested address:
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 404 /404.html;
error_page 403 /403.html;
error_page 405 =200 $uri;
}
If using proxy:
# If Nginx is like proxy for Apache:
error_page 405 =200 @405;
location @405 {
root /htdocs;
proxy_pass http://localhost:8080;
}
If using FastCGI:
location ~\.php(.*) {
fastcgi_pass 127.0.0.1:9000;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include /etc/nginx/fastcgi_params;
}
Browsers usually use GET, so you can use online tools like ApiTester to test your requests.
check your casing, the name is typically stored in upper case
SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;
If you just want to do a literal replace in java, use Pattern.quote(string)
to escape any string to a literal.
myString.replaceAll(Pattern.quote(matchingStr), replacementStr)
You don't need a derived table at all for this.
Just put the INTO
after the first SELECT
SELECT top(100)*
INTO tmpFerdeen
FROM Customers
UNION All
SELECT top(100)*
FROM CustomerEurope
UNION All
SELECT top(100)*
FROM CustomerAsia
UNION All
SELECT top(100)*
FROM CustomerAmericas
If i understand you correctly, (i probably don't)
'SELECT @RowCount = COUNT(*)
FROM dbo.Comm_Services
WHERE CompanyId = ' + CAST(@CompanyId AS CHAR) + '
AND ' + @condition
It's not smart to have python code inside java. Wrap your python code with flask or other web framework to make it as a microservice. Make your java program able to call this microservice (e.g. via REST).
Beleive me, this is much simple and will save you tons of issues. And the codes are loosely coupled so they are scalable.
Updated on Mar 24th 2020: According to @stx's comment, the above approach is not suitable for massive data transfer between client and server. Here is another approach I recommended: Connecting Python and Java with Rust(C/C++ also ok). https://medium.com/@shmulikamar/https-medium-com-shmulikamar-connecting-python-and-java-with-rust-11c256a1dfb0
You can use 100vw / 100vh
. CSS3 gives us viewport-relative units. 100vw means 100% of the viewport width. 100vh; 100% of the height.
<div style="display:flex; justify-content: space-between;background-color: lightyellow; width:100%; height:85vh">
<div style="width:70%; height: 100%; border: 2px dashed red"></div>
<div style="width:30%; height: 100%; border: 2px dashed red"></div>
</div>
HTML/CSS Approach
If you are looking for an option that does not require much JavaScript (and and all the problems that come with it, such as rapid scroll event calls), it is possible to gain the same behavior by adding a wrapper <div>
and a couple of styles. I noticed much smoother scrolling (no elements lagging behind) when I used the following approach:
HTML
<div id="wrapper">
<div id="fixed">
[Fixed Content]
</div><!-- /fixed -->
<div id="scroller">
[Scrolling Content]
</div><!-- /scroller -->
</div><!-- /wrapper -->
CSS
#wrapper { position: relative; }
#fixed { position: fixed; top: 0; right: 0; }
#scroller { height: 100px; overflow: auto; }
JS
//Compensate for the scrollbar (otherwise #fixed will be positioned over it).
$(function() {
//Determine the difference in widths between
//the wrapper and the scroller. This value is
//the width of the scroll bar (if any).
var offset = $('#wrapper').width() - $('#scroller').get(0).clientWidth;
//Set the right offset
$('#fixed').css('right', offset + 'px');?
});
Of course, this approach could be modified for scrolling regions that gain/lose content during runtime (which would result in addition/removal of scrollbars).
I just want to add that if the constructor is called from a different file, then something as simple as forgetting to export the constructor with
module.exports = NAME_OF_CONSTRUCTOR
will also cause the "Not a constructor" exception.
Function for check number is Decimal or whole number
function IsDecimalExist(p_decimalNumber) {
var l_boolIsExist = true;
if (p_decimalNumber % 1 == 0)
l_boolIsExist = false;
return l_boolIsExist;
}
In kotlin you can do:
// instantiate the new fragment
val fragment: Fragment = ExampleFragment()
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.book_description_fragment, fragment)
transaction.addToBackStack("transaction_name")
// Commit the transaction
transaction.commit()
How to Troubleshoot ORA-30926 Errors? (Doc ID 471956.1)
1) Identify the failing statement
alter session set events ‘30926 trace name errorstack level 3’;
or
alter system set events ‘30926 trace name errorstack off’;
and watch for .trc files in UDUMP when it occurs.
2) Having found the SQL statement, check if it is correct (perhaps using explain plan or tkprof to check the query execution plan) and analyze or compute statistics on the tables concerned if this has not recently been done. Rebuilding (or dropping/recreating) indexes may help too.
3.1) Is the SQL statement a MERGE? evaluate the data returned by the USING clause to ensure that there are no duplicate values in the join. Modify the merge statement to include a deterministic where clause
3.2) Is this an UPDATE statement via a view? If so, try populating the view result into a table and try updating the table directly.
3.3) Is there a trigger on the table? Try disabling it to see if it still fails.
3.4) Does the statement contain a non-mergeable view in an 'IN-Subquery'? This can result in duplicate rows being returned if the query has a "FOR UPDATE" clause. See Bug 2681037
3.5) Does the table have unused columns? Dropping these may prevent the error.
4) If modifying the SQL does not cure the error, the issue may be with the table, especially if there are chained rows. 4.1) Run the ‘ANALYZE TABLE VALIDATE STRUCTURE CASCADE’ statement on all tables used in the SQL to see if there are any corruptions in the table or its indexes. 4.2) Check for, and eliminate, any CHAINED or migrated ROWS on the table. There are ways to minimize this, such as the correct setting of PCTFREE. Use Note 122020.1 - Row Chaining and Migration 4.3) If the table is additionally Index Organized, see: Note 102932.1 - Monitoring Chained Rows on IOTs
I ran into a similar situation. I did have access to a larger data drive. Depending on your situation, and the access you have to the server you can consider
ln -s /datavol/path/to/your/.conda /home/user/.conda
Then subsequent conda commands will put data to the symlinked dir in datavol
You can do it without setlocal
, because of the setlocal
command the variable won't survive an endlocal
because it was created in setlocal
. In this way the variable will be defined the right way.
To do that use this code:
set var1=A
set var2=B
set AB=hi
call set newvar=%%%var1%%var2%%%
echo %newvar%
Note: You MUST use call
before you set the variable or it won't work.
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert($(myContent).text());
That results in hello world. Does that answer your question?
http://jsfiddle.net/D2tEf/ for an example
CDATA is a better general solution.
$(info your_text)
: Information. This doesn't stop the execution.
$(warning your_text)
: Warning. This shows the text as a warning.
$(error your_text)
: Fatal Error. This will stop the execution.
The accepted answer is correct regarding the Invoke-Command cmdlet, but more broadly speaking, cmdlets can have parameter sets where groups of input parameters are defined, such that you can't use two parameters that aren't members of the same parameter set.
If you're running into this error with any other cmdlet, look up its Microsoft documentation, and see if the the top of the page has distinct sets of parameters listed. For example, the documentation for Set-AzureDeployment defines three sets at the top of the page.
You have to set the http header at the http response of your resource. So it needs to be set serverside, you can remove the "HTTP_OPTIONS"-header from your angular HTTP-Post request.
you can use .parseXML
var xml='<Pages>
<Page Name="test">
<controls>
<test>this is a test.</test>
</controls>
</Page>
<page Name = "User">
<controls>
<name>Sunil</name>
</controls>
</page>
</Pages>';
jquery
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
$($xml).each(function(){
alert($(this).find("Page[Name]>controls>name").text());
});
here is the fiddle http://jsfiddle.net/R37mC/1/
Thank you for the code, it's just what I was looking for. I have also added the following code to Vimal's code, to implement the case of a CustomCellBackgroundViewPositionSingle cell. (All four corners are rounded.)
else if (position == CustomCellBackgroundViewPositionSingle)
{
CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ;
CGFloat miny = CGRectGetMinY(rect) , midy = CGRectGetMidY(rect) , maxy = CGRectGetMaxY(rect) ;
minx = minx + 1;
miny = miny + 1;
maxx = maxx - 1;
maxy = maxy - 1;
CGContextMoveToPoint(c, minx, midy);
CGContextAddArcToPoint(c, minx, miny, midx, miny, ROUND_SIZE);
CGContextAddArcToPoint(c, maxx, miny, maxx, midy, ROUND_SIZE);
CGContextAddArcToPoint(c, maxx, maxy, midx, maxy, ROUND_SIZE);
CGContextAddArcToPoint(c, minx, maxy, minx, midy, ROUND_SIZE);
// Close the path
CGContextClosePath(c);
// Fill & stroke the path
CGContextDrawPath(c, kCGPathFillStroke);
return;
}
this
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//toolbar.setNavigationIcon(R.drawable.ic_toolbar);
toolbar.setTitle("");
toolbar.setSubtitle("");
//toolbar.setLogo(R.drawable.ic_toolbar);
This issue can be resolved by trying multiple solutions like:
All will get executed and On first Called first run basis!!
<div id="target"></div>
<script>
$(document).ready(function(){
jQuery('#target').append('target edit 1<br>');
});
$(document).ready(function(){
jQuery('#target').append('target edit 2<br>');
});
$(document).ready(function(){
jQuery('#target').append('target edit 3<br>');
});
</script>
Demo As you can see they do not replace each other
Also one thing i would like to mention
in place of this
$(document).ready(function(){});
you can use this shortcut
jQuery(function(){
//dom ready codes
});
In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:
SELECT (p.column1, p.colum2, p.column3) FROM table1 p where p.column1 = 1;
And has to be:
SELECT p.column1, p.colum2, p.column3 FROM table1 p where p.column1 = 1;
Sounds silly, but it was causing this error and it took some time to figure it out.
From now on is better to use the .prop() function instead of the .attr() one.
Here the jQuery documentation:
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.
var div1Class = $('#div1').prop('class');
Lots of answers correctly state that calling textView.setSelected(true)
is required. However, if preferred to do so just via XML, one option could be to make use of the Binding Adapters when working with Data Binding.
So, just create a new adapter similar to:
@BindingAdapter("app:autoStartMarquee")
fun setAutoStartMarquee(textView: TextView, autoStartMarquee: Boolean) {
textView.isSelected = autoStartMarquee
}
Then, you can simply use it in the XML as follows:
...
<TextView
...
android:ellipsize="marquee"
android:singleLine="true"
app:autoStartMarquee="@{true}"/>
...
No need to call it from code anymore.
@stuXnet, I could make the exact opposite argument. If you pass an object to a function, and you change the properties of the passed object then the caller of the function will see the changed value in its variable. This implies a pass by reference system, not pass by value.
What is confusing is the definition of pass by value or pass by reference in a system where the use of pointers is completely hidden to the end user.
Java is definitely NOT pass by value, as to be such, would mean one could mutate the passed object and the original would be unaffected.
Notice you cannot mutate primitives you can only assign them to variables. So testing a Pass by reference or by value by using primitives is not a test.
What you cannot do in Java that can be done in other languages is to reassign the caller's variables to a new value because there are no pointers in Java, so this makes it confusing.
The main method of the runtime engine looks something like int main(int argc, char *argv[])
, where argc is a count of the number of arguments and argv is an array of pointers to each. The runtime engine converts this into a form that is more natural to c#.
Prior to that main method being called, everything is in assembly language. It has access to the command line arguments (because the operating system makes that available to every process that starts), but that assembly language needs to convert a single string of the full command line into multiple substrings (using whitespace to separate them) before it's ready to pass them into main().
prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox
Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):
erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"
erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"
erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"
erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"
@rem Clear IE cache - (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"
@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"
@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"
pause
I am pretty sure it will run for some time when you first run it :) Enjoy!
SELECT ...
SELECT SLEEP(5);
SELECT ...
But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?
There's actually no need for visibility
or opacity
- you can simply use color
, which has the upside of keeping any "blinking" to the text only:
blink {_x000D_
display: inline;_x000D_
color: inherit;_x000D_
animation: blink 1s steps(1) infinite;_x000D_
-webkit-animation: blink 1s steps(1) infinite;_x000D_
}_x000D_
@keyframes blink { 50% { color: transparent; } }_x000D_
@-webkit-keyframes blink { 50% { color: transparent; } }
_x000D_
Here is some text, <blink>this text will blink</blink>, this will not.
_x000D_
Fiddle: http://jsfiddle.net/2r8JL/
Maybe this can help :)
Controller
$scope.scrollevent = function($e){
// Your code
}
Html
<div scroll scroll-event="scrollevent">//scrollable content</div>
Or
<body scroll scroll-event="scrollevent">//scrollable content</body>
Directive
.directive("scroll", function ($window) {
return {
scope: {
scrollEvent: '&'
},
link : function(scope, element, attrs) {
$("#"+attrs.id).scroll(function($e) { scope.scrollEvent != null ? scope.scrollEvent()($e) : null })
}
}
})
<input type="email" name="email" id="email" value="" placeholder="Email" required />
documentation http://www.w3.org/TR/html-markup/input.email.html
For varchars, you may need to do something like this:
select convert(varchar(25), NULL) as abc_column into xyz_table
If you try
select '' as abc_column into xyz_table
you may get errors related to truncation, or an issue with null values, once you populate.
As others have mentioned, app on Android can't write a file to any folder the internal storage but their own private storage (which is under /data/data/PACKAGE_NAME ).
You should use the API to get the correct path that is allowed for your app.
read this .
On GKE, if the pod is dead, it's best to check for the events. It will show in more detail what the error is about.
In my case, I had :
Failed to pull image "gcr.io/project/imagename@sha256:c8e91af54fc17faa1c49e2a05def5cbabf8f0a67fc558eb6cbca138061a8400a":
rpc error: code = Unknown desc = error pulling image configuration: unknown blob
It turned out the image was damaged somehow. After repushing it and deploying with the new hash, it worked again.
As an extension method
public static IEnumerable<TSource> AreNotEqual<TSource, TKey, TTarget>(this IEnumerable<TSource> source, Func<TSource, TKey> sourceKeySelector, IEnumerable<TTarget> target, Func<TTarget, TKey> targetKeySelector)
{
var targetValues = new HashSet<TKey>(target.Select(targetKeySelector));
return source.Where(sourceValue => targetValues.Contains(sourceKeySelector(sourceValue)) == false);
}
eg.
public class Customer
{
public int CustomerId { get; set; }
}
public class OtherCustomer
{
public int Id { get; set; }
}
var customers = new List<Customer>()
{
new Customer() { CustomerId = 1 },
new Customer() { CustomerId = 2 }
};
var others = new List<OtherCustomer>()
{
new OtherCustomer() { Id = 2 },
new OtherCustomer() { Id = 3 }
};
var result = customers.AreNotEqual(customer => customer.CustomerId, others, other => other.Id).ToList();
Debug.Assert(result.Count == 1);
Debug.Assert(result[0].CustomerId == 1);
I got similar problem
1: I tried to resolve with the answer which is marked correct above But I was not able to get the system setting which was quit amazing (On MacBook).
Most of the time such errors & issues comes because of replacing your grade file with other grade file ,due which gradel does not sync properly and while building the project issue comes . The issue is bascially related to non syncing for platform tools
Solution a: Go to File and then to Your project strucutre -modules -app-Properties -build tool version -click on options which is required for your project (if required build tool version not there chose any other). This will sync the grade file and now you can go to gradel and change target version and build tool version as per your requirement .you will prompted to download the required platform tool to sync it , now click on install tool version and let project to build
Solution b: Try Anuja Ans if you can get option of system setting and install platform tool.
Answer has been moved here - https://stackoverflow.com/a/26944636/2377343
This was the best solution I found after more time than I care to admit. Basically, add target="_self" to each link that you need to insure a page reload.
http://blog.panjiesw.com/posts/2013/09/angularjs-normal-links-with-html5mode/
The other plus of using RecycleView
is animation, it can be done in two lines of code
RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
recyclerView.setItemAnimator(itemAnimator);
But the widget is still raw, e.g you can't create header and footer.
The answer about threading is good, but you need to be a bit more specific about what you want to do.
If you have two functions that both use a lot of CPU, threading (in CPython) will probably get you nowhere. Then you might want to have a look at the multiprocessing module or possibly you might want to use jython/IronPython.
If CPU-bound performance is the reason, you could even implement things in (non-threaded) C and get a much bigger speedup than doing two parallel things in python.
Without more information, it isn't easy to come up with a good answer.
You can use str_pad
for adding 0's
str_pad($month, 2, '0', STR_PAD_LEFT);
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....
So here's my answer and can be run out of the box.
<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">
<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {
$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})
$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end = $('#enddate').datepicker('getDate');
if (start<end) {
var days = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>
a Fiddle can be seen here DEMO
You basically need to run the installation again to rebuild the master
database with the new collation. You cannot change the entire server's collation any other way.
See:
Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:
SELECT name, collation_name
FROM sys.databases
WHERE name = 'test2' -- put your database name here
This will yield a value something like:
Latin1_General_CI_AS
The _CI
means "case insensitive" - if you want case-sensitive, use _CS
in its place:
Latin1_General_CS_AS
So your T-SQL command would be:
ALTER DATABASE test2 -- put your database name here
COLLATE Latin1_General_CS_AS -- replace with whatever collation you need
You can get a list of all available collations on the server using:
SELECT * FROM ::fn_helpcollations()
You can see the server's current collation using:
SELECT SERVERPROPERTY ('Collation')
How does spring know which polymorphic type to use.
As long as there is only a single implementation of the interface and that implementation is annotated with @Component
with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).
Do I need @Qualifier or @Resource?
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier
annotation to inject the right implementation, along with @Autowired
annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name
attribute of this annotation.
Why do we autowire the interface and not the implemented class?
Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.
interface IA
{
public void someFunction();
}
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Your bean configuration should look like this:
<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />
Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component
as follows:
interface IA
{
public void someFunction();
}
@Component(value="b")
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
@Component(value="c")
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
@Component
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Then worker
in MyRunner
will be injected with an instance of type B
.
<TextBlock Text="{Binding Date, StringFormat='{}{0:MM/dd/yyyy a\\t h:mm tt}'}" />
will return you
04/07/2011 at 1:28 PM (-04)
In C, \0
denotes a character with value zero. The following are identical:
char a = 0;
char b = '\0';
The utility of this escape sequence is greater inside string literals, which are arrays of characters:
char arr[] = "abc\0def\0ghi\0";
(Note that this array has two zero characters at the end, since string literals include a hidden, implicit terminal zero.)
The ".then()" function is wideley used for promised objects in Asynchoronus programming For Windows 8 Store Apps. As far as i understood it works some way like a callback.
Find Details in this Documentantion http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx
Of Cause it could also be the name for any other defined function.
As many said, there is no way to automatically convert without adding overheads and too much complexity, but you can reduce your typing a bit and make it look better by using lambdas if some cast will be used a bit much in a scenario. That would add a bit of function overhead call, but will make code more readable compared to long static_cast strings as can be seen below. This may not be useful project wide, but only class wide.
#include <bitset>
#include <vector>
enum class Flags { ......, Total };
std::bitset<static_cast<unsigned int>(Total)> MaskVar;
std::vector<Flags> NewFlags;
-----------
auto scui = [](Flags a){return static_cast<unsigned int>(a); };
for (auto const& it : NewFlags)
{
switch (it)
{
case Flags::Horizontal:
MaskVar.set(scui(Flags::Horizontal));
MaskVar.reset(scui(Flags::Vertical)); break;
case Flags::Vertical:
MaskVar.set(scui(Flags::Vertical));
MaskVar.reset(scui(Flags::Horizontal)); break;
case Flags::LongText:
MaskVar.set(scui(Flags::LongText));
MaskVar.reset(scui(Flags::ShorTText)); break;
case Flags::ShorTText:
MaskVar.set(scui(Flags::ShorTText));
MaskVar.reset(scui(Flags::LongText)); break;
case Flags::ShowHeading:
MaskVar.set(scui(Flags::ShowHeading));
MaskVar.reset(scui(Flags::NoShowHeading)); break;
case Flags::NoShowHeading:
MaskVar.set(scui(Flags::NoShowHeading));
MaskVar.reset(scui(Flags::ShowHeading)); break;
default:
break;
}
}
In very short
Encapsulation:– Information hiding
Abstraction :– Implementation hiding
Abstraction
lets you focus on what the object does
while Encapsulation means how an object works
The List
interface already has this solved.
int temp = 2;
if(bankAccNos.contains(bakAccNo)) temp=1;
More can be found in the documentation about List.
Update: For a more correct answer see Tim Down's answer.
Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like jQuery to handle the cross-browsers differences.
A really basic example is:
var xml = "<music><album>Beethoven</album></music>";
var result = $(xml).find("album").text();
Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.
>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
This should get the id added.
ASP.NET MVC 5 and lower:
<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "signupform" }))
{ } %>
ASP.NET Core: You can use tag helpers in forms to avoid the odd syntax for setting the id.
<form asp-controller="Account" asp-action="Register" method="post" id="signupform" role="form"></form>
Inspired by the insightful answers on this page, I created a mixed approach, which I consider the simplest and more flexible one. What do you think?
First, I define the usage in a variable, which allows me to reuse it in different contexts. The format is very simple, almost WYSIWYG, without the need to add any control characters. This seems reasonably portable to me (I ran it on MacOS and Ubuntu)
__usage="
Usage: $(basename $0) [OPTIONS]
Options:
-l, --level <n> Something something something level
-n, --nnnnn <levels> Something something something n
-h, --help Something something something help
-v, --version Something something something version
"
Then I can simply use it as
echo "$__usage"
or even better, when parsing parameters, I can just echo it there in a one-liner:
levelN=${2:?"--level: n is required!""${__usage}"}
This ended up being quite simple. chBoxListTables.Item[i] is a string value, and an explicit convert allowed it to be loaded into a variable. The following code works:
private void btnGO_Click(object sender, EventArgs e)
{
for (int i = 0; i < chBoxListTables.Items.Count; i++)
{
if (chBoxListTables.GetItemChecked(i))
{
string str = (string)chBoxListTables.Items[i];
MessageBox.Show(str);
}
}
}
Specify the /g
(global) flag on the regular expression to replace all matches instead of just the first:
string.replace(/_/g, ' ').replace(/#/g, '')
To replace one character with one thing and a different character with something else, you can't really get around needing two separate calls to replace
. You can abstract it into a function as Doorknob did, though I would probably have it take an object with old/new as key/value pairs instead of a flat array.
Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.
Two important pieces that are needed are:
$scope.entities = [{
"title": "foo",
"id": 1
}, {
"title": "bar",
"id": 2
}, {
"title": "baz",
"id": 3
}];
$scope.selected = [];
I usually start out with some combination of:
typeof(obj)
class(obj)
sapply(obj, class)
sapply(obj, attributes)
attributes(obj)
names(obj)
as appropriate based on what's revealed. For example, try with:
obj <- data.frame(a=1:26, b=letters)
obj <- list(a=1:26, b=letters, c=list(d=1:26, e=letters))
data(cars)
obj <- lm(dist ~ speed, data=cars)
..etc.
If obj
is an S3 or S4 object, you can also try methods
or showMethods
, showClass
, etc. Patrick Burns' R Inferno has a pretty good section on this (sec #7).
EDIT: Dirk and Hadley mention str(obj)
in their answers. It really is much better than any of the above for a quick and even detailed peek into an object.
Use this code between two words:
& vbCrLf &
Using this, the next word displays on the next line.
For using the new progress bar
style="?android:attr/progressBarStyleHorizontal"
for the old grey color progress bar use
style="@android:style/Widget.ProgressBar.Horizontal"
in this one you have the option of changing the height by setting minHeight
The complete XML code is:
<ProgressBar
android:id="@+id/pbProcessing"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tvProcessing"
android:indeterminateOnly="true"/>
indeterminateOnly is set to true for getting indeterminate horizontal progress bar
Handles either type of line break
str.replace(new RegExp('\r?\n','g'), '<br />');
Good news everybody! Craigslist has actually released a bulk posting api now!
You can't remove API functions without breaking the API. If you would, many applications would no longer compile or run at all.
This is the reason that one reference gives:
Reading a line that overflows the array pointed to by s results in undefined behavior. The use of fgets() is recommended.
Here you can find little JSON wrapper with corrective actions that addresses BOM and non-ASCI issue: https://stackoverflow.com/a/43694325/2254935
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.
Step 1: Simply put all the required code in a "MAIN.BAT" file.
Step 2: Create another bat file, say MainCaller.bat, and just copy/paste these 3 lines of code:
REM THE MAIN FILE WILL BE CALLED FROM HERE..........
CD "File_Path_Where_Main.bat_is_located"
MAIN.BAT > log.txt
Step 3: Just double click "MainCaller.bat".
All the output will be logged into the text file named "log".
Just put some CSS into the stylesheet like this
form {
text-align: center;
}
then you're done!
Great New Application
No Need to root your Phone and You Can Run your js File From anywere.
Update instruction to node js 8 (async await)
Download node.js v8.3.0 arm zip file and unzip.
copy 'node' to android's sdcard(/sdcard or /sdcard/path/to/...)
open the shell(check it out in the app's menu)
cd /data/user/0/io.tmpage.dorynode/files/bin (or, just type cd && cd .. && cd files/bin )
rm node
cp /sdcard/node .
(chmod a+x node
(https://play.google.com/store/apps/details?id=io.tempage.dorynode&hl=en)
The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables. The database engine puts the parameter value into where the placeholder is, and there is zero chance for SQL injection.
There is no sure-fire way of knowing that a request was made via Ajax. You can never trust data coming from the client. You could use a couple of different methods but they can be easily overcome by spoofing.
Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.
If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.
There are two solutions to fix this:
clear:both
after the last floated tag. This works good.overflow: hidden
Maybe something like this:
yourformName.YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);
Or if you are in the same class as the form then simply do this:
YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);
The constructor takes diffrent parameters (so pick your poison). Like this:
Font(Font, FontStyle)
Font(FontFamily, Single)
Font(String, Single)
Font(FontFamily, Single, FontStyle)
Font(FontFamily, Single, GraphicsUnit)
Font(String, Single, FontStyle)
Font(String, Single, GraphicsUnit)
Font(FontFamily, Single, FontStyle, GraphicsUnit)
Font(String, Single, FontStyle, GraphicsUnit)
Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte)
Font(String, Single, FontStyle, GraphicsUnit, Byte)
Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte, Boolean)
Font(String, Single, FontStyle, GraphicsUnit, Byte, Boolean)
Reference here
My naive assumption was that the size of scroll pane will be determined automatically...
The only solution that actually worked for me was explicitly seeting bounds of JScrollPane:
import javax.swing.*;
public class MyFrame extends JFrame {
public MyFrame()
{
setBounds(100, 100, 491, 310);
getContentPane().setLayout(null);
JTextArea textField = new JTextArea();
textField.setEditable(false);
String str = "";
for (int i = 0; i < 50; ++i)
str += "Some text\n";
textField.setText(str);
JScrollPane scroll = new JScrollPane(textField);
scroll.setBounds(10, 11, 455, 249); // <-- THIS
getContentPane().add(scroll);
setLocationRelativeTo ( null );
}
}
Maybe it will help some future visitors :)
Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.
Then you can just review the contents pre-update and write a SQL script to do the update.
You could do this using SUMIF
. This allows you to SUM a value in a cell IF a value in another cell meets the specified criteria. Here's an example:
- A B
1 100 YES
2 100 YES
3 100 NO
Using the formula: =SUMIF(B1:B3, "YES", A1:A3)
, you will get the result of 200
.
Here's a screenshot of a working example I just did in Excel:
You can access the elements in a list-of-lists by first specifying which list you're interested in and then specifying which element of that list you want. For example, 17
is element 2
in list 0
, which is list1[0][2]
:
>>> list1 = [[10,13,17],[3,5,1],[13,11,12]]
>>> list1[0][2]
17
So, your example would be
50 - list1[0][0] + list1[0][1] - list1[0][2]
left: initial
This will also set left
back to the browser default.
But important to know property: initial
is not supported in IE.
Call apply and bind. and how they are different.
Lets learn call and apply using any daily terminology.
You have three automobiles your_scooter , your_car and your_jet
which start with the same mechanism (method).
We created an object automobile
with a method push_button_engineStart
.
var your_scooter, your_car, your_jet;
var automobile = {
push_button_engineStart: function (runtime){
console.log(this.name + "'s" + ' engine_started, buckle up for the ride for ' + runtime + " minutes");
}
}
Lets understand when is call and apply used. Lets suppose that you are an engineer and you have your_scooter
, your_car
and your_jet
which did not come with a push_button_engine_start and you wish to use a third party push_button_engineStart
.
If you run the following lines of code, they will give an error. WHY?
//your_scooter.push_button_engineStart();
//your_car.push_button_engineStart();
//your_jet.push_button_engineStart();
automobile.push_button_engineStart.apply(your_scooter,[20]);
automobile.push_button_engineStart.call(your_jet,10);
automobile.push_button_engineStart.call(your_car,40);
So the above example is successfully gives your_scooter, your_car, your_jet a feature from automobile object.
Let's dive deeper
Here we will split the above line of code.
automobile.push_button_engineStart
is helping us to get the method being used.
Further we use apply or call using the dot notation.
automobile.push_button_engineStart.apply()
Now apply and call accept two parameters.
So here we set the context in the final line of code.
automobile.push_button_engineStart.apply(your_scooter,[20])
Difference between call and apply is just that apply accepts parameters in the form of an array while call simply can accept a comma separated list of arguments.
what is JS Bind function?
A bind function is basically which binds the context of something and then stores it into a variable for execution at a later stage.
Let's make our previous example even better. Earlier we used a method belonging to the automobile object and used it to equip your_car, your_jet and your_scooter
. Now lets imagine we want to give a separate push_button_engineStart
separately to start our automobiles individually at any later stage of the execution we wish.
var scooty_engineStart = automobile.push_button_engineStart.bind(your_scooter);
var car_engineStart = automobile.push_button_engineStart.bind(your_car);
var jet_engineStart = automobile.push_button_engineStart.bind(your_jet);
setTimeout(scooty_engineStart,5000,30);
setTimeout(car_engineStart,10000,40);
setTimeout(jet_engineStart,15000,5);
still not satisfied?
Let's make it clear as teardrop. Time to experiment. We will go back to call and apply function application and try storing the value of the function as a reference.
The experiment below fails because call and apply are invoked immediately, hence, we never get to the stage of storing a reference in a variable which is where bind function steals the show
var test_function = automobile.push_button_engineStart.apply(your_scooter);
private static string ToXml(Person obj)
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
string retval = null;
if (obj != null)
{
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
new XmlSerializer(obj.GetType()).Serialize(writer, obj,namespaces);
}
retval = sb.ToString();
}
return retval;
}
Did you remember setting the height of the html and body tags in your CSS? This is generally how I've gotten DIVs to extend to full height:
<html>
<head>
<style type="text/css">
html,body { height: 100%; margin: 0px; padding: 0px; }
#full { background: #0f0; height: 100% }
</style>
</head>
<body>
<div id="full">
</div>
</body>
</html>
I think you can use this way without using any css -
<table>
<tr>
<td>foo</td>
</tr>
<tr>
<td>bar</td>
</tr>
<tr>
<td>baz</td>
</tr>
</table>
Right now you are using block level element that way you are getting unwanted result. So you can you inline element like span, small etc.
<span>foo</span><span>bar</span><span>baz</span>
S.Lott inserted a comment, but it should be an answer: see the same question.
Since it wasn't as obvious as I intended it to be, here follows a verbatim copy of S.Lott's answer in the other question:
I'm a big fan of ARGO UML from Tigris.org. Draws nice pictures using standard UML notation. It does some code generation, but mostly Java classes, which isn't SQL DDL, so that may not be close enough to what you want to do.
You can look at the Data Modelling Tools list and see if anything there is better than Argo UML. Many of the items on this list are free or cheap.
Also, if you're using Eclipse or NetBeans, there are many design plug-ins, some of which may have the features you're looking for.
What I did was download both 2.7.6 and 3.3.4. Python 3.3.4 has the option to add the path to it in the environment variable so that was done. So basically I just manually added Python 2.7.6.
How to...
Start > in the search type in environment select "Edit environment variables to your account"1
Scroll down to Path, select path, click edit.
Add C:\Python27; so you should have paths to both versions of Python there, but if you don't this you can easily edit it so that you do..... C:\Python27;C:\Python33;
Navigate to the Python27 folder in C:\ and rename a copy of python.exe to python2.exe
Navigate to the Python34 folder in C:\ and rename a copy of python.exe to python3.exe
Test: open up commmand prompt and type python2 ....BOOM! Python 2.7.6. exit out.
Test: open up commmand prompt and type python3 ....BOOM! Python 3.4.3. exit out.
Note: (so as not to break pip commands in step 4 and 5, keep copy of python.exe in the same directory as the renamed file)
Good question. Similar to the observation you have about examples 1 and 4 (or should I say 1 & 4 :) ) over logical and
bitwise &
operators, I experienced on sum
operator. The numpy sum
and py sum
behave differently as well. For example:
Suppose "mat" is a numpy 5x5 2d array such as:
array([[ 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]])
Then numpy.sum(mat) gives total sum of the entire matrix. Whereas the built-in sum from Python such as sum(mat) totals along the axis only. See below:
np.sum(mat) ## --> gives 325
sum(mat) ## --> gives array([55, 60, 65, 70, 75])
java properties "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword" do not correspond to "server.ssl.trust-store" and "server.ssl.trust-store-password" from Spring boot "application.properties" ("application.yml")
so you can not set "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword" simply by setting "server.ssl.trust-store" and "server.ssl.trust-store-password" in "application.properties" ("application.yml")
an alternative of setting "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword" is by Spring boot Externalized Configuration
below are excerpts of my implementation :
Params class holds the external settings
@Component
@ConfigurationProperties("params")
public class Params{
//default values, can be override by external settings
public static String trustStorePath = "config/client-truststore.jks";
public static String trustStorePassword = "wso2carbon";
public static String keyStorePath = "config/wso2carbon.jks";
public static String keyStorePassword = "wso2carbon";
public static String defaultType = "JKS";
public void setTrustStorePath(String trustStorePath){
Params.trustStorePath = trustStorePath;
}
public void settrustStorePassword(String trustStorePassword){
Params.trustStorePassword=trustStorePassword;
}
public void setKeyStorePath(String keyStorePath){
Params.keyStorePath = keyStorePath;
}
public void setkeyStorePassword(String keyStorePassword){
Params.keyStorePassword = keyStorePassword;
}
public void setDefaultType(String defaultType){
Params.defaultType = defaultType;
}
KeyStoreUtil class undertakes the settings of "javax.net.ssl.trustStore" and "javax.net.ssl.trustStorePassword"
public class KeyStoreUtil {
public static void setTrustStoreParams() {
File filePath = new File( Params.trustStorePath);
String tsp = filePath.getAbsolutePath();
System.setProperty("javax.net.ssl.trustStore", tsp);
System.setProperty("javax.net.ssl.trustStorePassword", Params.trustStorePassword);
System.setProperty("javax.net.ssl.keyStoreType", Params.defaultType);
}
public static void setKeyStoreParams() {
File filePath = new File(Params.keyStorePath);
String ksp = filePath.getAbsolutePath();
System.setProperty("Security.KeyStore.Location", ksp);
System.setProperty("Security.KeyStore.Password", Params.keyStorePassword);
}
}
you get the setters executed within the startup function
@SpringBootApplication
@ComponentScan("com.myapp.profiles")
public class ProfilesApplication {
public static void main(String[] args) {
KeyStoreUtil.setKeyStoreParams();
KeyStoreUtil.setTrustStoreParams();
SpringApplication.run(ProfilesApplication.class, args);
}
}
Edited on 2018-10-03
you may also want to adopt the annotation "PostConstruct" as as an alternative to execute the setters
import javax.annotation.PostConstruct;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages={"com.xxx"})
public class GateApplication {
public static void main(String[] args) {
SpringApplication.run(GateApplication.class, args);
}
@PostConstruct
void postConstruct(){
setTrustStoreParams();
setKeyStoreParams();
}
private static void setTrustStoreParams() {
File filePath = new File( Params.trustStorePath);
String tsp = filePath.getAbsolutePath();
System.setProperty("javax.net.ssl.trustStore", tsp);
System.setProperty("javax.net.ssl.trustStorePassword", Params.trustStorePassword);
System.setProperty("javax.net.ssl.keyStoreType", Params.defaultType);
}
private static void setKeyStoreParams() {
File filePath = new File(Params.keyStorePath);
String ksp = filePath.getAbsolutePath();
System.setProperty("Security.KeyStore.Location", ksp);
System.setProperty("Security.KeyStore.Password", Params.keyStorePassword);
}
}
the application.yml
---
params:
trustStorePath: config/client-truststore.jks
trustStorePassword: wso2carbon
keyStorePath: config/wso2carbon.jks
keyStorePassword: wso2carbon
defaultType: JKS
---
finally, within the running environment(deployment server), you create a folder named "config" under the same folder where the jar archive is stored .
within the "config" folder, you store "application.yml", "client-truststore.jks", and "wso2carbon.jks". done!
Update on 2018-11-27 about Spring boot 2.x.x
starting from spring boot 2.x.x, static properties are no longer supported, please see here. I personally do not think it a good move, because complex changes have to be made along the reference chain...
anyway, an implementation excerpt might look like this
the 'Params' class
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.Data;
/**
* Params class represent all config parameters that can
* be external set by spring xml file
*/
@Component
@ConfigurationProperties("params")
@Data
public class Params{
//default values, can be override by external settings
public String trustStorePath = "config/client-truststore.jks";
public String trustStorePassword = "wso2carbon";
public String keyStorePath = "config/wso2carbon.jks";
public String keyStorePassword = "wso2carbon";
public String defaultType = "JKS";
}
the 'Springboot application class' (with 'PostConstruct')
import java.io.File;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages={"com.xx.xx"})
public class BillingApplication {
@Autowired
Params params;
public static void main(String[] args) {
SpringApplication.run(BillingApplication.class, args);
}
@PostConstruct
void postConstruct() {
// set TrustStoreParams
File trustStoreFilePath = new File(params.trustStorePath);
String tsp = trustStoreFilePath.getAbsolutePath();
System.setProperty("javax.net.ssl.trustStore", tsp);
System.setProperty("javax.net.ssl.trustStorePassword", params.trustStorePassword);
System.setProperty("javax.net.ssl.keyStoreType", params.defaultType);
// set KeyStoreParams
File keyStoreFilePath = new File(params.keyStorePath);
String ksp = keyStoreFilePath.getAbsolutePath();
System.setProperty("Security.KeyStore.Location", ksp);
System.setProperty("Security.KeyStore.Password", params.keyStorePassword);
}
}
For max value, we can write sql query as
select age from table_name order by age desc limit 1
same way we can write in mongodb too.
db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age
It is hard to handle multiple parameters on the action directly. The better way to do it is to create a view model class. Then you have a single parameter but the parameter contains multiple data properties.
public class MyParameters
{
public string a { get; set; }
public string b { get; set; }
}
public MyController : ApiController
{
public HttpResponseMessage Get([FromUri] MyParameters parameters) { ... }
}
Then you go to:
http://localhost:12345/api/MyController?a=par1&b=par2
Reference: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
If you want to use "/par1/par2", you can register an asp routing rule. eg routeTemplate: "API/{controller}/{action}/{a}/{b}".
See http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
Another approach could be using Array.prototype.forEach()
as
Array.from({_x000D_
length: 5_x000D_
}, () => Math.floor(Math.random() * 5)).forEach((val, index) => {_x000D_
console.log(val, index)_x000D_
})
_x000D_
Update (26SEP2016): It is no longer needed to uninstall your previous version of git to upgraded it to the latest; the installer package found at git win download site takes care of all. Just follow the prompts. For additional information follow instructions at installing and upgrading git.
Properties have values only in objects, not classes.
If you need to store something for all objects of a class, you have to use a global variable. You can hide it by declaring it static
in the implementation file.
You may also consider using specific relations between your objects: you attribute a role of master to a specific object of your class and link others objects to this master. The master will hold the dictionary as a simple property. I think of a tree like the one used for the view hierarchy in Cocoa applications.
Another option is to create an object of a dedicated class that is composed of both your 'class' dictionary and a set of all the objects related to this dictionary. This is something like NSAutoreleasePool
in Cocoa.
This is an ultimate solution to set the border color of a TextBox:
public class BorderedTextBox : UserControl
{
TextBox textBox;
public BorderedTextBox()
{
textBox = new TextBox()
{
BorderStyle = BorderStyle.FixedSingle,
Location = new Point(-1, -1),
Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
AnchorStyles.Left | AnchorStyles.Right
};
Control container = new ContainerControl()
{
Dock = DockStyle.Fill,
Padding = new Padding(-1)
};
container.Controls.Add(textBox);
this.Controls.Add(container);
DefaultBorderColor = SystemColors.ControlDark;
FocusedBorderColor = Color.Red;
BackColor = DefaultBorderColor;
Padding = new Padding(1);
Size = textBox.Size;
}
public Color DefaultBorderColor { get; set; }
public Color FocusedBorderColor { get; set; }
public override string Text
{
get { return textBox.Text; }
set { textBox.Text = value; }
}
protected override void OnEnter(EventArgs e)
{
BackColor = FocusedBorderColor;
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e)
{
BackColor = DefaultBorderColor;
base.OnLeave(e);
}
protected override void SetBoundsCore(int x, int y,
int width, int height, BoundsSpecified specified)
{
base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
}
}
If we assume the date in Excel is in A1 cell formatted as Date and the Unix timestamp should be in a A2 cell formatted as number the formula in A2 should be:
= (A1 * 86400) - 2209075200
where:
86400 is the number of seconds in the day 2209075200 is the number of seconds between 1900-01-01 and 1970-01-01 which are the base dates for Excel and Unix timestamps.
The above is true for Windows. On Mac the base date in Excel is 1904-01-01 and the seconds number should be corrected to: 2082844800
Depending on why you are doing this, using a std::set might be a better idea than std::vector.
It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.
This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.
There are two way to stop current method/process :
Option : you can also kill the current thread to stop it.
For example :
public void onClick(){
if(condition == true){
return;
<or>
throw new YourException();
}
string.setText("This string should not change if condition = true");
}
This reply may be late but it may help users having similar problem. The opencv-contrib (available at https://github.com/opencv/opencv_contrib/releases) contains extra modules but the build procedure has to be done from core opencv (available at from https://github.com/opencv/opencv/releases) modules.
Follow below steps (assuming you are building it using CMake GUI)
Download openCV (from https://github.com/opencv/opencv/releases) and unzip it somewhere on your computer. Create build folder inside it
Download exra modules from OpenCV. (from https://github.com/opencv/opencv_contrib/releases). Ensure you download the same version.
Unzip the folder.
Open CMake
Click Browse Source and navigate to your openCV folder.
Click Browse Build and navigate to your build Folder.
Click the configure button. You will be asked how you would like to generate the files. Choose Unix-Makefile from the drop down menu and Click OK. CMake will perform some tests and return a set of red boxes appear in the CMake Window.
Search for "OPENCV_EXTRA_MODULES_PATH" and provide the path to modules folder (e.g. /Users/purushottam_d/Programs/OpenCV3_4_5_contrib/modules)
Click Configure again, then Click Generate.
Go to build folder
# cd build
# make
# sudo make install
Build a new list with a list comprehension:
new_items = [x if x % 2 else None for x in items]
You can modify the original list in-place if you want, but it doesn't actually save time:
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for index, item in enumerate(items):
if not (item % 2):
items[index] = None
Here are (Python 3.6.3) timings demonstrating the non-timesave:
In [1]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: for index, item in enumerate(items):
...: if not (item % 2):
...: items[index] = None
...:
1.06 µs ± 33.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [2]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: new_items = [x if x % 2 else None for x in items]
...:
891 ns ± 13.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
And Python 2.7.6 timings:
In [1]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: for index, item in enumerate(items):
...: if not (item % 2):
...: items[index] = None
...:
1000000 loops, best of 3: 1.27 µs per loop
In [2]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: new_items = [x if x % 2 else None for x in items]
...:
1000000 loops, best of 3: 1.14 µs per loop
I have tried the above answers and the best i think is this one
@item.First_Name.Substring(0,1)
In this i could get the first letter of the string
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
Open python console:
import platform
platform.architecture()[0]
it should display the '64bit' or '32bit' according to your platform.
Alternatively( in case of OS X binaries ):
import sys
sys.maxsize > 2**32
# it should display True in case of 64bit and False in case of 32bit
step 1 Copy this class in your package
step 2 put the following code in your class which extends SQLiteOpenHelper.
//-----------------for show databasae table----------------------------------------
public ArrayList<Cursor> getData(String Query)
{
//get writable database
SQLiteDatabase sqlDB =this.getWritableDatabase();
String[] columns = new String[] { "mesage" };
//an array list of cursor to save two cursors one has results from the query
//other cursor stores error message if any errors are triggered
ArrayList<Cursor> alc = new ArrayList<Cursor>(2);
MatrixCursor Cursor2= new MatrixCursor(columns);
alc.add(null);
alc.add (null);
try{
String maxQuery = Query ;
//execute the query results will be save in Cursor c
Cursor c = sqlDB.rawQuery(maxQuery, null);
//add value to cursor2
Cursor2.addRow(new Object[] { "Success" });
alc.set(1,Cursor2);
if (null != c && c.getCount() > 0)
{
alc.set(0,c);
c.moveToFirst();
return alc ;
}
return alc;
}
catch(SQLException sqlEx)
{
Log.d("printing exception", sqlEx.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+sqlEx.getMessage() });
alc.set(1,Cursor2);
return alc;
}
catch(Exception ex)
{
Log.d("printing exception",ex.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+ex.getMessage() });
alc.set(1,Cursor2);
return alc;
}
}
step 3 register in manifest
<activity
android:name=".database.AndroidDatabaseManager"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar"/>
step 4
Intent i = new Intent(this, AndroidDatabaseManager.class);
startActivity(i);
In Java, List
is an interface. That is, it cannot be instantiated directly.
Instead you can use ArrayList
which is an implementation of that interface that uses an array as its backing store (hence the name).
Since ArrayList
is a kind of List
, you can easily upcast it:
List<T> mylist = new ArrayList<T>();
This is in contrast with .NET, where, since version 2.0, List<T>
is the default implementation of the IList<T>
interface.
Adding to Eric Jablow's answer, here is a possible solution (it worked for me - linux mint 14 /nadia)
find /path/to/search/ -type f -name "glob-to-find-files" | xargs cp -t /target/path/
You can refer to "How can I use xargs to copy files that have spaces and quotes in their names?" as well.
If you prefer a GUI, DB Browser for SQLite will do this with a few clicks.
DB Browser for SQLite is open source and free. For Linux it is available from the repository.
As @diyism mentioned, "default_socket_timeout, stream_set_timeout, and stream_context_create timeout are all the timeout of every line read/write, not the whole connection timeout." And the top answer by @stewe has failed me.
As an alternative to using file_get_contents
, you can always use curl
with a timeout.
So here's a working code that works for calling links.
$url='http://example.com/';
$ch=curl_init();
$timeout=5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result=curl_exec($ch);
curl_close($ch);
echo $result;
I've experienced the same problem and now I just found my solution to this issue.
#!/usr/bin/python
import sys
import os
os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))
This is the code[1] for my case. When I tried this script I received error message like :
import: command not found
I found people talks about the shebang. As you see there is the shebang in my python code above. I tried these and those trials but didn't find a good solution.
I finally tried to type the shebang my self.
#!/usr/bin/python
and removed the copied one.
And my problem solved!!!
I copied the code from the internet[1].
And I guess there had been some unseeable(?) unseen special characters in the original copied shebang statement.
I use vim, sometimes I experience similar problems.. Especially when I copied some code snippet from the internet this kind of problems happen.. Web pages have some virus special characters!! I doubt. :-)
Journeyer
PS) I copied the code in Windows 7 - host OS - into the Windows clipboard and pasted it into my vim in Ubuntu - guest OS. VM is Oracle Virtual Machine.
[1] http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy
Then create your object with that index.
Note: this will still have same issues other answers have described with respect to enforcing the type of each item - but that's often exactly what you want.
You can make the generic type parameter whatever you need : ObjectIndexer< Dog | Cat>
// this should be global somewhere, or you may already be
// using a library that provides such a type
export interface ObjectIndexer<T> {
[id: string]: T;
}
interface ISomeObject extends ObjectIndexer<string>
{
firstKey: string;
secondKey: string;
thirdKey: string;
}
let someObject: ISomeObject = {
firstKey: 'firstValue',
secondKey: 'secondValue',
thirdKey: 'thirdValue'
};
let key: string = 'secondKey';
let secondValue: string = someObject[key];
You can even use this in a generic constraint when defining a generic type:
export class SmartFormGroup<T extends IndexableObject<any>> extends FormGroup
Then T
inside the class can be indexed :-)
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
As its name suggests, twoord.plot()
in the plotrix package plots with two ordinate axes.
library(plotrix)
example(twoord.plot)
HTML:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
jQuery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
Here is a function I wrote to solve this issue (assuming tag has no attributes). This function will keep HTML formatting in the node:
function getAsXMLContent($xmlElement)
{
$content=$xmlElement->asXML();
$end=strpos($content,'>');
if ($end!==false)
{
$tag=substr($content, 1, $end-1);
return str_replace(array('<'.$tag.'>', '</'.$tag.'>'), '', $content);
}
else
return '';
}
$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);
echo getAsXMLContent($xml->child); // prints Hello World
Put in other words, this error is telling you that SQL Server does not know which B
to select from the group.
Either you want to select one specific value (e.g. the MIN
, SUM
, or AVG
) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B
in the GROUP BY
field list).
Consider the following data:
ID A B 1 1 13 1 1 79 1 2 13 1 2 13 1 2 42
The query
SELECT A, COUNT(B) AS T1
FROM T2
GROUP BY A
would return:
A T1 1 2 2 3
which is all well and good.
However consider the following (illegal) query, which would produce this error:
SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A
And its returned data set illustrating the problem:
A T1 B 1 2 13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...? 2 3 13? 42? ...?
However, the following two queries make this clear, and will not cause the error:
Using an aggregate
SELECT A, COUNT(B) AS T1, SUM(B) AS B
FROM T2
GROUP BY A
would return:
A T1 B 1 2 92 2 3 68
Adding the column to the GROUP BY
list
SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A, B
would return:
A T1 B 1 1 13 1 1 79 2 2 13 2 1 42
Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate
is a date input field in template.
import {formatDate} from '@angular/common';
this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));
I had the same problem with an Ubuntu Linux server running subversion when accessed via Eclipse.
It has shown that the problem had to do with a warning when Apache (re)started:
[Mon Jun 30 22:27:10 2014] [warn] NameVirtualHost *:80 has no VirtualHosts
... waiting [Mon Jun 30 22:27:11 2014] [warn] NameVirtualHost *:80 has no VirtualHosts
This has been due to a new entry in ports.conf
, where another NameVirtualHost
directive was entered alongside the directive in sites-enabled/000-default
.
After removing the directive in ports.conf
, the problem had vanished (after restarting Apache, naturally)
Full guide with pyenv
If pyenv is not installed then install it with pyenv-installer:
$ curl https://pyenv.run | bash
To use any custom python version, e.g. 3.5.6
use the following:
pyenv install 3.5.6
pyenv virtualenv 3.5.6 NAME_OF_YOUR_ENV
cd YOUR_PROJECT_PATH
pyenv local NAME_OF_YOUR_ENV
From the Command Prompt (Start \ All Programs \ Accessories \ Command Prompt):
DEL /S SqlStudio.bin
From documentation of the warnings
module:
#!/usr/bin/env python -W ignore::DeprecationWarning
If you're on Windows: pass -W ignore::DeprecationWarning
as an argument to Python. Better though to resolve the issue, by casting to int.
(Note that in Python 3.2, deprecation warnings are ignored by default.)
There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:
MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.
Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (
.
) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs.+
and.-
are unnecessary.
If you don't mind destroying the array (or a temp copy of it) you can do:
$stack = array("orange", "banana", "apple", "raspberry");
while ($fruit = array_pop($stack)){
echo $fruit . "\n<br>";
}
produces:
raspberry
apple
banana
orange
I think this solution reads cleaner than fiddling with an index and you are less likely to introduce index handling mistakes, but the problem with it is that your code will likely take slightly longer to run if you have to create a temporary copy of the array first. Fiddling with an index is likely to run faster, and it may also come in handy if you actually need to reference the index, as in:
$stack = array("orange", "banana", "apple", "raspberry");
$index = count($stack) - 1;
while($index > -1){
echo $stack[$index] ." is in position ". $index . "\n<br>";
$index--;
}
But as you can see, you have to be very careful with the index...
I noticed creation of 'appcompat' library while creating new android project with ADT 22.6.2 version, even when the minSDK was set to 11 and targetSDK was set 19
This was happening because, in the new project template android is using some attributes that are from the support library. For instance if a new project was created with actionbar then in the menu's main.xml one could find app:showAsAction="never"
which is from support library.
android:showAsAction
in menu's main.xmlAlso the default theme set could be "Theme.AppCompat.Light.DarkActionBar" as shown below (styles.xml)
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- API 14 theme customizations can go here. -->
</style>
In this case the parent theme in style.xml has to be changed to "android:style/Theme.Holo.Light.DarkActionBar"
Since .NET Framework 4.5 and .NET Standard 1.0 you should use WebUtility.UrlEncode
. Advantages over alternatives:
It is part of .NET Framework 4.5+, .NET Core 1.0+, .NET Standard 1.0+, UWP 10.0+ and all Xamarin platforms as well. HttpUtility
, while being available in .NET Framework earlier (.NET Framework 1.1+), becomes available on other platforms much later (.NET Core 2.0+, .NET Standard 2.0+) and it still unavailable in UWP (see related question).
In .NET Framework, it resides in System.dll
, so it does not require any additional references, unlike HttpUtility
.
It properly escapes characters for URLs, unlike Uri.EscapeUriString
(see comments to drweb86's answer).
It does not have any limits on the length of the string, unlike Uri.EscapeDataString
(see related question), so it can be used for POST requests, for example.
The php option mysql.connect_timeout
is the reason for this. It's not only used for connect timeout, but as well as waiting for the first answer from the server. You can increase it like this:
ini_set('mysql.connect_timeout', 300);
ini_set('default_socket_timeout', 300);
The following regex is for space inclusion in textbox.
Regex r = new Regex("^[a-zA-Z\\s]+");
r.IsMatch(textbox1.text);
This works fine for me.
Why use java.awt.Robot when org.openqa.selenium.interactions.Actions.class would probably work fine? Just sayin.
Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL)
.click(someElement)
.moveByOffset( 10, 25 );
.click(someOtherElement)
.keyUp(Keys.CONTROL).build().perform();
If you have a QMainWindow
you can override closeEvent
method.
#include <QCloseEvent>
void MainWindow::closeEvent (QCloseEvent *event)
{
QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,
tr("Are you sure?\n"),
QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
if (resBtn != QMessageBox::Yes) {
event->ignore();
} else {
event->accept();
}
}
If you're subclassing a QDialog
, the closeEvent
will not be called and so you have to override reject()
:
void MyDialog::reject()
{
QMessageBox::StandardButton resBtn = QMessageBox::Yes;
if (changes) {
resBtn = QMessageBox::question( this, APP_NAME,
tr("Are you sure?\n"),
QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
}
if (resBtn == QMessageBox::Yes) {
QDialog::reject();
}
}
this is my full solution which would read any base64 image format and save it in the proper format in the database:
// Save base64 image to disk
try
{
// Decoding base-64 image
// Source: http://stackoverflow.com/questions/20267939/nodejs-write-base64-image-file
function decodeBase64Image(dataString)
{
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var response = {};
if (matches.length !== 3)
{
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
}
// Regular expression for image type:
// This regular image extracts the "jpeg" from "image/jpeg"
var imageTypeRegularExpression = /\/(.*?)$/;
// Generate random string
var crypto = require('crypto');
var seed = crypto.randomBytes(20);
var uniqueSHA1String = crypto
.createHash('sha1')
.update(seed)
.digest('hex');
var base64Data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAZABkAAD/4Q3zaHR0cDovL25zLmFkb2JlLmN...';
var imageBuffer = decodeBase64Image(base64Data);
var userUploadedFeedMessagesLocation = '../img/upload/feed/';
var uniqueRandomImageName = 'image-' + uniqueSHA1String;
// This variable is actually an array which has 5 values,
// The [1] value is the real image extension
var imageTypeDetected = imageBuffer
.type
.match(imageTypeRegularExpression);
var userUploadedImagePath = userUploadedFeedMessagesLocation +
uniqueRandomImageName +
'.' +
imageTypeDetected[1];
// Save decoded binary image to disk
try
{
require('fs').writeFile(userUploadedImagePath, imageBuffer.data,
function()
{
console.log('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath);
});
}
catch(error)
{
console.log('ERROR:', error);
}
}
catch(error)
{
console.log('ERROR:', error);
}
Building on @ShadowCloud 's example I was able to dynamically include all routes in a sub directory.
routes/index.js
var fs = require('fs');
module.exports = function(app){
fs.readdirSync(__dirname).forEach(function(file) {
if (file == "index.js") return;
var name = file.substr(0, file.indexOf('.'));
require('./' + name)(app);
});
}
Then placing route files in the routes directory like so:
routes/test1.js
module.exports = function(app){
app.get('/test1/', function(req, res){
//...
});
//other routes..
}
Repeating that for as many times as I needed and then finally in app.js placing
require('./routes')(app);
If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.
TaskCompletionSource<bool> tcs = null;
private async void Button_Click(object sender, RoutedEventArgs e)
{
tcs = new TaskCompletionSource<bool>();
await tcs.Task;
WelcomeTitle.Text = "Finished work";
}
private void Button_Click2(object sender, RoutedEventArgs e)
{
tcs?.TrySetResult(true);
}
This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change
await tcs.Task;
to
await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
WelcomeTitle.Text = "Task Completed";
else
WelcomeTitle.Text = "Task Timed Out";
Your best bet will be looking at the WifiManager class. Specifically the setWifiEnabled(bool)
function.
See the documentation at: http://developer.android.com/reference/android/net/wifi/WifiManager.html#setWifiEnabled(boolean)
A tutorial on how to use it (including what permissions you need) can be found here: http://www.tutorialforandroid.com/2009/10/turn-off-turn-on-wifi-in-android-using.html
you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.
so if you want your code to work just put.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
Using Concat on the group by will work
SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30
I case you are running SpringBoot:
I just had the same problem, that I could not Autowire one of my services from the static main method.
See below an approach in case you are relying on SpringApplication.run:
@SpringBootApplication
public class PricingOnlineApplication {
@Autowired
OrchestratorService orchestratorService;
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(PricingOnlineApplication.class, args);
PricingOnlineApplication application = context.getBean(PricingOnlineApplication.class);
application.start();
}
private void start() {
orchestratorService.performPricingRequest(null);
}
}
I noticed that SpringApplication.run returns a context which can be used similar to the above described approaches. From there, it is exactly the same as above ;-)
mysqli in PHP 5 is an object with some good functions that will allow you to speed up the insertion time for the answer above:
$mysqli->autocommit(FALSE);
$mysqli->multi_query($sqlCombined);
$mysqli->autocommit(TRUE);
Turning off autocommit when inserting many rows greatly speeds up insertion, so turn it off, then execute as mentioned above, or just make a string (sqlCombined) which is many insert statements separated by semi-colons and multi-query will handle them fine.
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
Following Chrome Lighthouse recommendations for a faster application load, I have asynced my Javascript:
views/layout/application.html.erb
<%= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload', async: true %>
This broke everything and got that Token error for my remote forms. Removing async: true
fixed the problem.
borrowed this shamely from here
Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
More information here
JavaScript doesn't have a built-in init()
function, that is, it's not a part of the language. But it's not uncommon (in a lot of languages) for individual programmers to create their own init()
function for initialisation stuff.
A particular init()
function may be used to initialise the whole webpage, in which case it would probably be called from document.ready or onload processing, or it may be to initialise a particular type of object, or...well, you name it.
What any given init()
does specifically is really up to whatever the person who wrote it needed it to do. Some types of code don't need any initialisation.
function init() {
// initialisation stuff here
}
// elsewhere in code
init();
You can put custom image in radiobutton like normal button. for that create one XML file in drawable folder e.g
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sub_screens_aus_hl"
android:state_pressed="true"/>
<item android:drawable="@drawable/sub_screens_aus"
android:state_checked="true"/>
<item android:drawable="@drawable/sub_screens_aus"
android:state_focused="true" />
<item android:drawable="@drawable/sub_screens_aus_dis" />
</selector>
Here you can use 3 different images for radiobutton
and use this file to RadioButton like:
android:button="@drawable/aus"
android:layout_height="120dp"
android:layout_width="wrap_content"
Yes, right click the project. Click Run as
then Run Configurations
. You can change the parameters passed to the JVM in the Arguments
tab in the VM Arguments
box.
That configuration can then be used as the default when running the project.
You need a new version of notepad++. Looks like old versions don't support |
.
Note: egrep "CAT|TOWN"
will search for lines containing CATOWN. (CAT)|(TOWN)
is the proper or extension (matching 1,3,4). Strangely you wrote and which is btw (CAT.*TOWN)|(TOWN.*CAT)
There is a HOC included for React-Table that allows for selection, even when filtering and paginating the table, the setup is slightly more advanced than the basic table so read through the info in the link below first.
After importing the HOC you can then use it like this with the necessary methods:
/**
* Toggle a single checkbox for select table
*/
toggleSelection(key: number, shift: string, row: string) {
// start off with the existing state
let selection = [...this.state.selection];
const keyIndex = selection.indexOf(key);
// check to see if the key exists
if (keyIndex >= 0) {
// it does exist so we will remove it using destructing
selection = [
...selection.slice(0, keyIndex),
...selection.slice(keyIndex + 1)
];
} else {
// it does not exist so add it
selection.push(key);
}
// update the state
this.setState({ selection });
}
/**
* Toggle all checkboxes for select table
*/
toggleAll() {
const selectAll = !this.state.selectAll;
const selection = [];
if (selectAll) {
// we need to get at the internals of ReactTable
const wrappedInstance = this.checkboxTable.getWrappedInstance();
// the 'sortedData' property contains the currently accessible records based on the filter and sort
const currentRecords = wrappedInstance.getResolvedState().sortedData;
// we just push all the IDs onto the selection array
currentRecords.forEach(item => {
selection.push(item._original._id);
});
}
this.setState({ selectAll, selection });
}
/**
* Whether or not a row is selected for select table
*/
isSelected(key: number) {
return this.state.selection.includes(key);
}
<CheckboxTable
ref={r => (this.checkboxTable = r)}
toggleSelection={this.toggleSelection}
selectAll={this.state.selectAll}
toggleAll={this.toggleAll}
selectType="checkbox"
isSelected={this.isSelected}
data={data}
columns={columns}
/>
See here for more information:
https://github.com/tannerlinsley/react-table/tree/v6#selecttable
Here is a working example:
https://codesandbox.io/s/react-table-select-j9jvw
You could avoid hardcoding the full path by setting a JS variable in the header of your template, before wp_head()
is called, holding the template URL. Like:
<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>
And use that variable to set the background (I realize you know how to do this, I only include these details in case they helps others):
Reset.style.background = " url('"+templateUrl+"/images/searchfield_clear.png') ";
Many answers here recommend using synchronized.
However, it depends on the usecase.
The synchronized keyword has naturally built in language support. This can mean the JIT can optimise synchronised blocks in ways it cannot with Locks. e.g. it can combine synchronized blocks. Only one thread is allowed to access only one method at any given point of time using a synchronized block. This is a very expensive operation.
Locks avoid this by allowing configuration of various locks for different purpose. One can have couple of methods synchronized under one lock and other methods under a different lock. This allows more concurrency and also increases overall performance.
So, for a smaller system which can do without concurrency and allowing one thread to execute an operation, synchronized can work. Otherwise, lock can be taken on the key.
Had a similar problem when starting apache jmeter on windows 8 64 bit:
[]apache-jmeter-2.13\bin>jmeter
java.util.prefs.WindowsPreferences <init>
WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.
Successfully used Dennis Traub solution, with Mkorsch explanations. Or you can create a file with the extension "reg" and write into it the following:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Prefs]
... then execute it.
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
node -v
v9.10.1
If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value
So I would suggest use JSON.stringify
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname, query = parsedUrl.query;
const method = req.method;
res.end("hello world\n");
console.log(`Request received on: ${path} + method: ${method} + query:
${JSON.stringify(query)}`);
console.log('query: ', query);
});
server.listen(3000, () => console.log("Server running at port 3000"));
So doing curl http://localhost:3000/foo\?fizz\=buzz
will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}
Assuming that you already downloaded chromeDriver, this error is also occurs when already multiple chrome tabs are open.
If you close all tabs and run again, the error should clear up.
<script type="text/javascript">
function iframeDidLoad() {
alert('Done');
}
function newSite() {
var sites = ['http://getprismatic.com',
'http://gizmodo.com/',
'http://lifehacker.com/']
document.getElementById('myIframe').src = sites[Math.floor(Math.random() * sites.length)];
}
</script>
<input type="button" value="Change site" onClick="newSite()" />
<iframe id="myIframe" src="http://getprismatic.com/" onLoad="iframeDidLoad();"></iframe>
Example at http://jsfiddle.net/MALuP/