As an answer I say No. You can only get values from jstl to javascript. But u can display the user name using javascript itself. Best ways are here. To display user name, if u have html like
<div id="uName"></div>
You can display user name as follows.
var val1 = document.getElementById('userName').value;
document.getElementById('uName').innerHTML = val1;
var userName = '<c:out value="${user}"/>';
here ${user} is the data you get as response(from backend).
var arrayLength = <c:out value="${details.size()}"/>;
function advanced(){
var values = new Array();
<c:if test="${empty details.users}">
values.push("No user found");
</c:if>
<c:if test="${!empty details.users}">
<c:forEach var="user" items="${details.users}" varStatus="stat">
values.push("${user.name}");
</c:forEach>
</:c:if>
alert("values[0] "+values[0]);
});
First navigate to below location and open it in a text editor
<TOMCAT_HOME>/conf/tomcat-users.xml
For tomcat 7, Add the following xml code somewhere between <tomcat-users>
<role rolename="manager-gui"/>
<user username="username" password="password" roles="manager-gui"/>
Now restart the tomcat server.
Yes you can use ALTER TABLE
as follows:
ALTER TABLE [table name] ALTER COLUMN [column name] [data type] NULL
Quoting from the ALTER TABLE
documentation:
NULL
can be specified inALTER COLUMN
to force aNOT NULL
column to allow null values, except for columns in PRIMARY KEY constraints.
By using AppCompat textAllCaps
in Android Apps supporting older API's (less than 14)
There is one UI widgets that ships with AppCompat named CompatTextView is a Custom TextView extension that adds support for textAllCaps
For newer android API > 14 you can use :
android:textAllCaps="true"
A simple example:
<android.support.v7.internal.widget.CompatTextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:textAllCaps="true"/>
Source:developer.android
Update:
As it so happens CompatTextView was replaced by AppCompatTextView in latest appcompat-v7 library ~ Eugen Pechanec
I guess you looking for CURDATE()
or NOW()
.
SELECT name, datum
FROM tasks
WHERE datum >= CURDATE()
LooK the rsult of NOW and CURDATE
NOW() CURDATE()
2008-11-11 12:45:34 2008-11-11
Yes you can go to File -> Settings -> Editor -> Auto Import -> Java and make the following changes:
1.change Insert imports on paste value to All in drop down option.
2.markAdd unambigious imports on the fly option as checked.(For Window or linux user)
On a Mac, do the same thing in Android Studio -> Preferences
3.You can also use Eclipse shortcut key in Android Studio just go to in Android Studio
File -> Settings -> KeyMap -> Keymaps dropdown Option. Select from them
Thankyou
data = sc.textFile('path_to_data')
header = data.first() #extract header
data = data.filter(row => row != header) #filter out header
scaleLabel : "<%= Number(value).toFixed(2).replace('.', ',') + ' $'%>"
File->Project Structure->Project pane->"Android plugin version".
Make sure you don't confuse the Gradle version with the Android plugin version. The former is the build system itself, the latter is the plugin to the build system that knows how to build Android projects
You can run the packager on another port.
$ react-native start --port=8088
Alternatively, find out what is using which ports on Windows with netstat.
$ netstat -a -b -o
Netstat gives you a PID, which you can use to kill the process.
$ taskkill /pid 1234
Strings do have a length method: __len__()
The protocol in Python is to implement this method on objects which have a length and use the built-in len()
function, which calls it for you, similar to the way you would implement __iter__()
and use the built-in iter()
function (or have the method called behind the scenes for you) on objects which are iterable.
See Emulating container types for more information.
Here's a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment
In the default constructor (and any non-default ones if you have any too of course):
public foo() {
Bar = "bar";
}
This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.
This is guaranteed to have nothing to do with the compiler. All compilers do is compile the code that they are given. What you're looking for is a GUI library, which you can write code against using any compiler that you want.
Of course, that being said, your first order of business should be to ditch Turbo C. That compiler is about 20 years old and continuing to use it isn't doing you any favors. You can't write modern GUI applications, as it will only produce 16-bit code. All modern operating systems are 32-bit, and many are now 64-bit. It's also worth noting that 64-bit editions of Windows will not run 16-bit applications natively. You'll need an emulator for that; it's not really going to engender much feeling of accomplishment if you can only write apps that work in a DOS emulator. :-)
Microsoft's Visual Studio Express C++ is available as a free download. It includes the same compiler available in the full version of the suite. The C++ package also compiles pure C code.
And since you're working in Windows, the Windows API is a natural choice. It allows you to write native Windows applications that have access to the full set of GUI controls. You'll find a nice tutorial here on writing WinAPI applications in C. If you choose to go with Visual Studio, it also includes boilerplate code for a blank WinAPI application that will get you up and running quickly.
If you really care about learning to do this, Charles Petzold's Programming Windows is the canonical resource of the subject, and definitely worth a read. The entire Windows API was written in C, and it's entirely possible to write full-featured Windows applications in C. You don't need no stinkin' C++.
That's the way I'd do it, at least. As the other answers suggest, GTK is also an option. But the applications it generates are just downright horrible-looking on Windows.
EDIT: Oh dear... It looks like you're not alone in wanting to write "GUI" applications using an antiquated compiler. A Google search turns up the following library: TurboGUI: A GUI Framework for Turbo C/C++:
If you're another one of those poor people stuck in the hopelessly out-of-date Indian school system and forced to use Turbo C to complete your education, this might be an option. I'm loathe to recommend it, as learning to work around its limitations will be completely useless to you once you graduate, but apparently it's out there for you if you're interested.
new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(input)
print(df.to_csv(sep='\t', index=False))
Or possibly:
print(df.to_csv(columns=['A', 'B', 'C'], sep='\t', index=False))
SET @customerID=0;
SELECT @customerID:=@customerID+1 AS customerID
FROM CUSTOMER ;
you can obtain the dataset from SQL like this and populate it into a java data structure (like a List) and then make the necessary sorting over there. (maybe with the help of a comparable interface)
Most important reason according to this article on DZone:
String Constant Pool ... If string is mutable, changing the string with one reference will lead to the wrong value for the other references.
Security
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. ...
Hope it will help you.
I've found a couple other ways you can write these which are a bit more readable IMHO.
- name: check out a git repository
local_action:
module: git
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
OR
- name: check out a git repository
local_action: git
args:
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
Finally i found the problem i was using metro framework and all your solutions will not work with metroTextBox, and all your solutions will work with normal textBox in load , show , visibility_change ,events, even the tab index = 0 is valid.
// private void Form1_VisibleChanged(object sender, EventArgs e)
// private void Form1__Shown(object sender, EventArgs e)
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Select();
this.ActiveControl=textBox1;
textBox1.Focus();
}
I didn't need to set up remote debugging in order to get this working, I used Maven.
spring-boot::run
.NB. If your IDE has problems finding your project's source code when doing line-by-line debugging, take a look at this SO answer to find out how to manually attach your source code to the debug application.
Hope this helps someone!
There is an implementation in my TypeScript utilities based on JavaScript GUID generators.
Here is the code:
class Guid {_x000D_
static newGuid() {_x000D_
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
var r = Math.random() * 16 | 0,_x000D_
v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
return v.toString(16);_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
var id = Guid.newGuid();_x000D_
console.log(id);_x000D_
}
_x000D_
Please note the following:
C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.
JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).
go to Start->Run and type cmd this starts the Command Prompt (also available from Start->Programs->Accessories->Command Prompt)
type cd .. and press return type cd .. and press return again (keep doing this until the prompt shows :> )
now you need to go to a special folder which might be c:\windows\system32 or it might be c:\winnt\system32 or it might be c:\windows\sysWOW64 try typing each of these eg cd c:\windows\sysWOW64 (if it says The system cannot find the path specified, try the next one) cd c:\windows\system32 cd c:\winnt\system32 when one of those doesn't cause an error, stop, you've found the correct folder.
now you need to register the OLE DB 4.0 DLLs by typing these commands and pressing return after each
regsvr32 Msjetoledb40.dll regsvr32 Msjet40.dll regsvr32 Mswstr10.dll regsvr32 Msjter40.dll regsvr32 Msjint40.dll
Use adb kill-server
. It should helps.
or
adb -s emulator-5554 emu kill
, where emulator-5554
is the emulator name.
For Ubuntu users I found a good command to stop all running emulators (Thanks to @uwe)
adb devices | grep emulator | cut -f1 | while read line; do adb -s $line emu kill; done
There are at least three different types of logging:
The logging BEFORE the program is executed, which only logs IF the cronjob TRIED to execute the command. That one is located in /var/log/syslog, as already mentioned by @Matthew Lock.
The logging of errors AFTER the program tried to execute, which can be sent to an email or to a file, as mentioned by @Spliffster. I prefer logging to a file, because with email THEN you have a NEW source of problems, and its checking if email sending and reception is working perfectly. Sometimes it is, sometimes it's not. For example, in a simple common desktop machine in which you are not interested in configuring an smtp, sometimes you will prefer logging to a file:
* * * * COMMAND_ABSOLUTE_PATH > /ABSOLUTE_PATH_TO_LOG 2>&1
There are some common sources of problems with cronjobs: * The ABSOLUTE PATH of the binary to be executed. When you run it from your shell, it might work, but the cron process seems to use another environment, and hence it doesn't always find binaries if you don't use the absolute path. * The LIBRARIES used by a binary. It's more or less the same previous point, but make sure that, if simply putting the NAME of the command, is referring to exactly the binary which uses the very same library, or better, check if the binary you are referring with the absolute path is the very same you refer when you use the console directly. The binaries can be found using the locate command, for example:
$locate python
Be sure that the binary you will refer, is the very same the binary you are calling in your shell, or simply test again in your shell using the absolute path that you plan to put in the cronjob.
index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
#messages { margin-bottom: 40px }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
window.scrollTo(0, document.body.scrollHeight);
});
});
</script>
</body>
</html>
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
And run these commands for run the application.
npm init; // accept defaults
npm install socket.io http --save ;
node start
and open the URL:- http://127.0.0.1:3000/
Port may be different.
and you will see this OUTPUT
Integer.valueOf(android.os.Build.VERSION.SDK);
Values are:
Platform Version API Level
Android 9.0 28
Android 8.1 27
Android 8.0 26
Android 7.1 25
Android 7.0 24
Android 6.0 23
Android 5.1 22
Android 5.0 21
Android 4.4W 20
Android 4.4 19
Android 4.3 18
Android 4.2 17
Android 4.1 16
Android 4.0.3 15
Android 4.0 14
Android 3.2 13
Android 3.1 12
Android 3.0 11
Android 2.3.3 10
Android 2.3 9
Android 2.2 8
Android 2.1 7
Android 2.0.1 6
Android 2.0 5
Android 1.6 4
Android 1.5 3
Android 1.1 2
Android 1.0 1
CAUTION: don't use android.os.Build.VERSION.SDK_INT
if <uses-sdk android:minSdkVersion="3" />
.
You will get exception on all devices with Android 1.5 and lower because Build.VERSION.SDK_INT
is since SDK 4 (Donut 1.6).
git checkout stash@{N} <File(s)/Folder(s) path>
Eg. To restore only ./test.c file and ./include folder from last stashed,
git checkout stash@{0} ./test.c ./include
If you use a unary plus to convert a string to a number as documented on MDN.
For example:+discount.toFixed(2)
The latter alternative is used for methods on mocks that return void
.
Please have a look, for example, here: How to make mock to void methods with mockito
Note that this solution works if the commit to be removed is the last committed one.
1 - Copy the commit reference you like to go back to from the log:
git log
2 - Reset git to the commit reference:
git reset <commit_ref>
3 - Stash/store the local changes from the wrong commit to use later after pushing to remote:
git stash
4 - Push the changes to remote repository, (-f or --force):
git push -f
5 - Get back the stored changes to local repository:
git stash apply
7 - In case you have untracked/new files in the changes, you need to add them to git before committing:
git add .
6 - Add whatever extra changes you need, then commit the needed files, (or use a dot '.' instead of stating each file name, to commit all files in the local repository:
git commit -m "<new_commit_message>" <file1> <file2> ...
or
git commit -m "<new_commit_message>" .
I used the code mentioned in this great answer and expanded it to support 2 additional parameters which I needed in my case. The parameters are file extensions to filter on and a flag indicating whether to concatenate the full path to the name of the file or not.
I hope it is clear enough and someone will finds it beneficial.
function fileList = getAllFiles(dirName, fileExtension, appendFullPath)
dirData = dir([dirName '/' fileExtension]); %# Get the data for the current directory
dirWithSubFolders = dir(dirName);
dirIndex = [dirWithSubFolders.isdir]; %# Find the index for directories
fileList = {dirData.name}'; %'# Get a list of the files
if ~isempty(fileList)
if appendFullPath
fileList = cellfun(@(x) fullfile(dirName,x),... %# Prepend path to files
fileList,'UniformOutput',false);
end
end
subDirs = {dirWithSubFolders(dirIndex).name}; %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'}); %# Find index of subdirectories
%# that are not '.' or '..'
for iDir = find(validIndex) %# Loop over valid subdirectories
nextDir = fullfile(dirName,subDirs{iDir}); %# Get the subdirectory path
fileList = [fileList; getAllFiles(nextDir, fileExtension, appendFullPath)]; %# Recursively call getAllFiles
end
end
Example for running the code:
fileList = getAllFiles(dirName, '*.xml', 0); %#0 is false obviously
I tried to use the Cast Extension (see https://stackoverflow.com/users/247402/stacker) in a situation where the Target Type contains a Property that is not present in the Source Type. It did not work, I'm not sure why. I refactored to the following extension that did work for my situation:
public static T Casting<T>(this Object source)
{
Type sourceType = source.GetType();
Type targetType = typeof(T);
var target = Activator.CreateInstance(targetType, false);
var sourceMembers = sourceType.GetMembers()
.Where(x => x.MemberType == MemberTypes.Property)
.ToList();
var targetMembers = targetType.GetMembers()
.Where(x => x.MemberType == MemberTypes.Property)
.ToList();
var members = targetMembers
.Where(x => sourceMembers
.Select(y => y.Name)
.Contains(x.Name));
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
value = source.GetType().GetProperty(memberInfo.Name).GetValue(source, null);
propertyInfo.SetValue(target, value, null);
}
return (T)target;
}
Note that I changed the name of the extension as the Name Cast conflicts with results from Linq. Hat tip https://stackoverflow.com/users/2093880/usefulbee
Emacs! Eclipse might work too.
You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the
tag (that you are looking for). The corresponding example from the documentation is as follows
For example, here is a comment that refers to the getComponentAt(int, int) method:
Use the {@link #getComponentAt(int, int) getComponentAt} method.
The package.class
part can be ommited if the referred method is in the current class.
Other useful links about JavaDoc are:
git remote show origin
Enter passphrase for key ....ssh/id_rsa:
* remote origin
Fetch URL: [email protected]:mamaque/systems.git
Push URL: [email protected]:mamaque/systems.git
HEAD branch: main
Remote branch:
main tracked
Local ref configured for 'git push':
main pushes to main (up-to-date)
Both are up to date
main pushes to main (fast-forwardable)
Remote can be updated with Local
main pushes to main (local out of date)
Local can be update with Remote
Do a (recursive) Revert operation from a level above the directory you deleted.
Edit If you are asking about security, see my addendum at the bottom Edit
PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.
$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);
This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.
Addendum
I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.
FYI, [ChildActionOnly] is not available in ASP.NET MVC Core. see some info here
-- Delete index if exists
IF EXISTS(SELECT TOP 1 1 FROM sys.indexes indexes INNER JOIN sys.objects
objects ON indexes.object_id = objects.object_id WHERE indexes.name
='Your_Index_Name' AND objects.name = 'Your_Table_Name')
BEGIN
PRINT 'DROP INDEX [Your_Index_Name] ON [dbo].[Your_Table_Name]'
DROP INDEX [our_Index_Name] ON [dbo].[Your_Table_Name]
END
GO
You got this Error because you tried to convert column DataType
from String
to int
which is
leagal if and only if
you dont have row in that table with string content inside that column
so just make sure your previously inserted Rows is compatible with the new changes
I would tackle the problem like this:
BufferedWriter output;
output = new BufferedWriter(new FileWriter("file.txt", true));
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
output.append(sizeX);
output.append(sizeY);
output.newLine();
output.close();
The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?
If you have more than one element with the same ID, then you have invalid HTML.
But you can acheive the same result using classes instead. That's what they're designed for.
<input class='b' ... >
You can give it an ID as well if you need to, but it should be unique.
Once you've got the class in there, you can reference it with a dot instead of the hash, like so:
var value = $('#a .b').val();
or
var value = $('#a input.b').val();
which will limit it to 'b' class elements that are inputs within the form (which seems to be close to what you're asking for).
First off you can't have just a number for your id unless you are using the HTML5 DOCTYPE. Secondly, you need to either remove the # in each id or replace it with this:
$container.cycle(id.replace('#',''));
I just added a padding-top to the div below the nav. Hope it helps. I'm new on this. C:
#nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
margin: 0 auto;
padding: 0;
background: url(../css/patterns/black_denim.png);
z-index: 9999;
}
#container {
display: block;
padding: 6em 0 3em;
}
On the Mac, there's webkit2png and on Linux+KDE, you can use khtml2png. I've tried the former and it works quite well, and heard of the latter being put to use.
I recently came across QtWebKit which claims to be cross platform (Qt rolled WebKit into their library, I guess). But I've never tried it, so I can't tell you much more.
The QtWebKit links shows how to access from Python. You should be able to at least use subprocess to do the same with the others.
data
will return you a string representation of a list, but it is actually still a string. Just check the type of data
with type(data)
. That means if you try using indexing on this string representation of a list as such data['fruits'][0]
, it will return you "[" as it is the first character of data['fruits']
You can do json.loads(data['fruits'])
to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here
1-firstly, drop the foreign key constraint after that drop the tables.
2-you can drop all foreign key via executing the following query:
DECLARE @SQL varchar(4000)=''
SELECT @SQL =
@SQL + 'ALTER TABLE ' + s.name+'.'+t.name + ' DROP CONSTRAINT [' + RTRIM(f.name) +'];' + CHAR(13)
FROM sys.Tables t
INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id
INNER JOIN sys.schemas s ON s.schema_id = f.schema_id
--EXEC (@SQL)
PRINT @SQL
if you execute the printed results @SQL, the foreign keys will be dropped.
As of powershell 5.0, you can now use the -Depth
parameter in Get-ChildItem
!
You combine it with -Recurse
to limit the recursion.
Get-ChildItem -Recurse -Depth 2
The main problem was that you were opening/closing files repeatedly inside your loop.
Try this approach:
with open('new.txt') as text_file, open('xyz.txt', 'w') as myfile:
for line in text_file:
var1, var2 = line.split(",");
myfile.write(var1+'\n')
We open both files at once and because we are using with
they will be automatically closed when we are done (or an exception occurs). Previously your output file was repeatedly openend inside your loop.
We are also processing the file line-by-line, rather than reading all of it into memory at once (which can be a problem when you deal with really big files).
Note that write()
doesn't append a newline ('\n'
) so you'll have to do that yourself if you need it (I replaced your writelines()
with write()
as you are writing a single item, not a list of items).
When opening a file for r
read, the 'r'
is optional since it's the default mode.
First I will check the python3
path where it lives
And then in the VS Code settings just add that path, for example:
"python.pythonPath": "/usr/local/bin/python3"
As the official docs of redux suggest, better to export the unconnected component as well.
In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component:
import { connect } from 'react-redux'
// Use named export for unconnected component (for tests)
export class App extends Component { /* ... */ }
// Use default export for the connected component (for app)
export default connect(mapStateToProps)(App)
Since the default export is still the decorated component, the import statement pictured above will work as before so you won't have to change your application code. However, you can now import the undecorated App components in your test file like this:
// Note the curly braces: grab the named export instead of default export
import { App } from './App'
And if you need both:
import ConnectedApp, { App } from './App'
In the app itself, you would still import it normally:
import App from './App'
You would only use the named export for tests.
50 - List1[0][0] + List[0][1] - List[0][2]
List[0]
gives you the first list in the list (try out print List[0]
). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0]
.
If your class2 looks like this having static members
public class2
{
static int var = 1;
public static void myMethod()
{
// some code
}
}
Then you can simply call them like
class2.myMethod();
class2.var = 1;
If you want to access non-static members then you would have to instantiate an object.
class2 object = new class2();
object.myMethod(); // non static method
object.var = 1; // non static variable
DATEDIFF() is designed to return the number boundaries crossed between the two dates for the span specified. To get it to do what you want, you need to make an additional adjustment to account for when the dates cross a boundary but don't complete the full span.
goto is not in Java
you have to use GOTO But it don't work correctly.in key java word it is not used. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
public static void main(String[] args) {
GOTO me;
//code;
me:
//code;
}
}
CREATE TABLE #tempww (
LoginName nvarchar(max),
DBname nvarchar(max),
Username nvarchar(max),
AliasName nvarchar(max)
)
INSERT INTO #tempww
EXEC master..sp_msloginmappings
-- display results
declare @col varchar(1000)
declare @sql varchar(2000)
select @col = COALESCE(@col + ', ','') + QUOTENAME(DBname)
from #tempww Group by DBname
Set @sql='select * from (select LoginName,Username,AliasName,DBname,row_number() over(order by (select 0)) rn from #tempww) src
PIVOT (Max(rn) FOR DBname
IN ('+@col+')) pvt'
EXEC(@sql)
-- cleanup
DROP TABLE #tempww
I've found the following code to be the most robust (c++11). It catches both integers and floats.
#include <regex>
bool isNumber( std::string token )
{
return std::regex_match( token, std::regex( ( "((\\+|-)?[[:digit:]]+)(\\.(([[:digit:]]+)?))?" ) ) );
}
airline @ Github looks good. It is based on annotation and is trying to emulate Git command line structures.
Find extension=php_soap.dll
or extension=soap
in php.ini and remove the commenting semicolon at the beginning of the line. Eventually check for soap.ini
under the conf.d directory.
Restart your server.
Apache
sudo apt-get install php7.0-soap
sudo systemctl restart apache2
PHP5
sudo apt-get install php-soap
sudo systemctl restart apache2
Apache
sudo zypper in php7-soap
sudo systemctl restart apache2
Nginx
sudo zypper in php7-soap
sudo systemctl restart nginx
you do not need to pull 'picture' attribute though. there is much more convenient way, the only thing you need is userid, see example below;
https://graph.facebook.com/user_id/picture?type=large
p.s. type defines the size you want
plz keep in mind that using token with basic permissions, /me/friends will return list of friends only with id+name attributes
Try this simpler one,
cp /home/ankur/folder/file{1,2} /home/ankur/dest
If you want to copy all the 10 files then run this command,
cp ~/Desktop/{xyz,file{1,2},next,files,which,are,not,similer} foo-bar
Quick answer: No, at least not with native SMS service.
Long answer: Sure, but the receiver's phone should have the correct setup first. An app that detects incoming sms, and if a keyword matches, reports its current location to your server, which then pushes that info to the sender.
If you have Java 6 (You should have, btw) or higher, then simply do this :
Console console = System.console();
String str = console.readLine("Please enter the xxxx : ");
Please remember to do :
import java.io.Console;
Thats it!
I use two classes. First one the cache core object:
public class Cacher<TValue>
where TValue : class
{
#region Properties
private Func<TValue> _init;
public string Key { get; private set; }
public TValue Value
{
get
{
var item = HttpRuntime.Cache.Get(Key) as TValue;
if (item == null)
{
item = _init();
HttpContext.Current.Cache.Insert(Key, item);
}
return item;
}
}
#endregion
#region Constructor
public Cacher(string key, Func<TValue> init)
{
Key = key;
_init = init;
}
#endregion
#region Methods
public void Refresh()
{
HttpRuntime.Cache.Remove(Key);
}
#endregion
}
Second one is list of cache objects:
public static class Caches
{
static Caches()
{
Languages = new Cacher<IEnumerable<Language>>("Languages", () =>
{
using (var context = new WordsContext())
{
return context.Languages.ToList();
}
});
}
public static Cacher<IEnumerable<Language>> Languages { get; private set; }
}
It isn't a tag…
But if you have it, you risk having white space after it.
If you then use it as an include at the top of a document, you could end up inserting white space (i.e. content) before you attempt to send HTTP headers … which isn't allowed.
Here is my solution: http://jsfiddle.net/agamemnus/g56aw709/-- code below.
All one needs to do is to convert their ":hover" to ".hover"... that's it! The big difference between this and the rest is that this will also work on non-singular element selectors such as .my_class > *:hover {
.
handle_css_hover_effects ()
function handle_css_hover_effects (init) {
var init = init || {}
var handle_touch_events = init.handle_touch_events || true
var handle_mouse_events = init.handle_mouse_events || true
var hover_class = init.hover_class || "hover"
var delay_preferences = init.delay_preferences || {touch: {add: 500, remove: 500}}
function default_handler (curobj, input_type, op) {
var hovered_element_selector = "*" + ((op == "add") ? ":" : ("." + hover_class))
var hovered_elements = Array.prototype.slice.call(document.body.querySelectorAll(hovered_element_selector))
var modified_list = []
while (true) {
if ((curobj == null) || (curobj == document.documentElement)) break
if (hovered_elements.indexOf(curobj) != -1) modified_list.push (curobj)
curobj = curobj.parentNode
}
function do_hover_change () {modified_list.forEach (function (curobj) {curobj.classList[op](hover_class)})}
if ((!delay_preferences[input_type]) || (!delay_preferences[input_type][op])) {
do_hover_change ()
} else {
setTimeout (do_hover_change, delay_preferences[input_type][op])
}
}
if (handle_mouse_events) {
document.body.addEventListener ('mouseover' , function (evt) {var curobj = evt.target; default_handler (curobj, "mouse", "add")})
document.body.addEventListener ('mouseout' , function (evt) {var curobj = evt.target; default_handler (curobj, "mouse", "remove")})
document.body.addEventListener ('click' , function (evt) {var curobj = evt.target; default_handler (curobj, "mouse", "remove")})
}
if (handle_touch_events) {
document.body.addEventListener ('touchstart', function (evt) {var curobj = evt.target; default_handler (curobj, "touch", "add")})
document.body.addEventListener ('touchend' , function (evt) {var curobj = evt.target; default_handler (curobj, "touch", "remove")})
document.body.addEventListener ('touchmove', function (evt) {
var curobj = evt.target
var hovered_elements = Array.prototype.slice.call(document.body.querySelectorAll("*:hover"))
var lastobj = null
evt = evt.changedTouches[0]
var elements_at_point = get_elements_at_point (evt.pageX, evt.pageY)
// Get the last element that isn't at the current point but is still hovered over, and remove only its hover attribute.
while (true) {
if ((curobj == null) || (curobj == document.documentElement)) break
if ((hovered_elements.indexOf(curobj) != -1) && (elements_at_point.indexOf(curobj) == -1)) lastobj = curobj
curobj = curobj.parentNode
}
if (lastobj == null) return
if ((!delay_preferences.touch) || (!delay_preferences.touch.remove)) {
lastobj.classList.remove(hover_class)
} else {
setTimeout (function () {lastobj.classList.remove(hover_class)}, delay_preferences.touch.remove)
}
function get_elements_at_point (x, y) {
var el_list = [], pe_list = []
while (true) {
var curobj = document.elementFromPoint(x, y)
if ((curobj == null) || (curobj == document.documentElement)) break
el_list.push (curobj); pe_list.push (curobj.style.pointerEvents)
curobj.style.pointerEvents = "none"
}
el_list.forEach (function (current_element, i) {current_element.style.pointerEvents = pe_list[i]})
return el_list
}
})
}
}
<html>
<head>
<title>Page</title>
</head>
<body>
<a href="./">Folder directory</a>
</body>
</html>
Only thing worked for me.
Open the project -> Select your target -> Go to Build Settings -> Search PROVISIONING and delete the selected profiles.
MySQL supports Spatial data types and Point
is a single-value type which can be used. Example:
CREATE TABLE `buildings` (
`coordinate` POINT NOT NULL,
/* Even from v5.7.5 you can define an index for it */
SPATIAL INDEX `SPATIAL` (`coordinate`)
) ENGINE=InnoDB;
/* then for insertion you can */
INSERT INTO `buildings`
(`coordinate`)
VALUES
(POINT(40.71727401 -74.00898606));
For Python 3.7, use subprocess.call. Use raw string to simplify the Windows paths:
import subprocess
subprocess.call([r'C:\Temp\Example\Notepad.exe', 'C:\test.txt'])
The "this" is already coloured in Javascript.
View->Syntax-> and choose your language to highlight.
From your code it becomes apparent that you use POCO. Having another key is unnecessary: you can add an index as suggested by juFo.
If you use Fluent API instead of attributing UserName property your column annotation should look like this:
this.Property(p => p.UserName)
.HasColumnAnnotation("Index", new IndexAnnotation(new[] {
new IndexAttribute("Index") { IsUnique = true }
}
));
This will create the following SQL script:
CREATE UNIQUE NONCLUSTERED INDEX [Index] ON [dbo].[Users]
(
[UserName] ASC
)
WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF,
DROP_EXISTING = OFF,
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
If you attempt to insert multiple Users having the same UserName you'll get a DbUpdateException with the following message:
Cannot insert duplicate key row in object 'dbo.Users' with unique index 'Index'.
The duplicate key value is (...).
The statement has been terminated.
Again, column annotations are not available in Entity Framework prior to version 6.1.
You can also pass date format
df.withColumn("Date",to_date(unix_timestamp(df.col("your_date_column"), "your_date_format").cast("timestamp")))
For Example
import org.apache.spark.sql.functions._
val df = sc.parallelize(Seq("06 Jul 2018")).toDF("dateCol")
df.withColumn("Date",to_date(unix_timestamp(df.col("dateCol"), "dd MMM yyyy").cast("timestamp")))
In typeScript you can do something like this:
if (object.prop1 && object.prop1.prop2 && object.prop1.prop2.prop3) {
const items = object.prop1.prop2.prop3
console.log(items);
}
For all to those having problems with this i did this tutorial:
How to install Imagemagick and Php module Imagick on ubuntu?
i did this 7 simple steps:
Update libraries, and packages
apt-get update
Remove obsolete things
apt-get autoremove
For the libraries of ImageMagick
apt-get install libmagickwand-dev
for the core class Imagick
apt-get install imagemagick
For create the binaries, and conections in beetween
pecl install imagick
Append the extension to your php.ini
echo "extension=imagick.so" >> /etc/php5/apache2/php.ini
Restart Apache
service apache2 restart
I found a problem. PHP searches for .so files in a folder called /usr/lib/php5/20100525, and the imagick.so is stored in a folder called /usr/lib/php5/20090626. So you have to copy the file to that folder.
Try put this in the head of the document:
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico"/>
The line would be as shown below:
Dim x As Integer
x = dgvName.Rows(yourRowIndex).Cells(yourColumnIndex).Value
To make it read only
@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @readonly="true"})
To diable
@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @disabled="true"})
For Apache 2.4, you would use the Require IP directive. So to only allow machines from the 192.168.0.0/24 network (range 192.168.0.0 - 192.168.0.255)
<VirtualHost *:80>
<Location />
Require ip 192.168.0.0/24
</Location>
...
</VirtualHost>
And if you just want the localhost machine to have access, then there's a special Require local directive.
The local provider allows access to the server if any of the following conditions is true:
- the client address matches 127.0.0.0/8
- the client address is ::1
- both the client and the server address of the connection are the same
This allows a convenient way to match connections that originate from the local host:
<VirtualHost *:80>
<Location />
Require local
</Location>
...
</VirtualHost>
Most often, when $('#myModal').modal('show');
doesn't work, it's caused by having included jQuery twice. Including jQuery 2 times makes modals not to work.
Remove one of the links to make it work again.
Furthermore, some plugins cause errors too, in this case add
jQuery.noConflict();
$('#myModal').modal('show');
public class ArrayToString {
public static void main(String[] args) { String[] strArray = new String[]{"Java", "PHP", ".NET", "PERL", "C", "COBOL"};String newString = Arrays.toString(strArray); newString = newString.substring(1, newString.length()-1); System.out.println("New New String: " + newString); } }
Also, if your PATH's dir is enclosed in quotes, it will work from the command prompt but you'll get the same error message
I.e. this causes an issue with Process.Start() not finding your exe:
PATH="C:\my program\bin";c:\windows\system32
Maybe it helps someone.
If you want to duplicate the table with all its constraints & keys follows this below steps:
Then for copying the data run this below script:
SET IDENTITY_INSERT DuplicateTable ON
INSERT Into DuplicateTable ([Column1], [Column2], [Column3], [Column4],... )
SELECT [Column1], [Column2], [Column3], [Column4],... FROM MainTable
SET IDENTITY_INSERT DuplicateTable OFF
Use the zzz
format specifier to get the timezone offset as hours and minutes. You also want to use the HH
format specifier to get the hours in 24 hour format.
DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")
Result:
2011-08-09T23:49:58+02:00
Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:
DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")
This code block solve my problem,
<script type="text/javascript">_x000D_
$(window).bind("load", function () {_x000D_
// Code here_x000D_
});_x000D_
</script>
_x000D_
I was hoping to add this as a comment to Marcus Westin's reply, but I can't find a link - maybe I need more reputation?
Anyway, thanks, I found this code snippet useful for quick debugging in IE. I have made some quick tweaks to fix a problem that stopped it working for me, also to scroll down automatically and use fixed positioning so it will appear in the viewport. Here's my version in case anyone finds it useful:
myLog = function() {
var _div = null;
this.toJson = function(obj) {
if (typeof window.uneval == 'function') { return uneval(obj); }
if (typeof obj == 'object') {
if (!obj) { return 'null'; }
var list = [];
if (obj instanceof Array) {
for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
return '[' + list.join(',') + ']';
} else {
for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
return '{' + list.join(',') + '}';
}
} else if (typeof obj == 'string') {
return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
} else {
return new String(obj);
}
};
this.createDiv = function() {
myLog._div = document.body.appendChild(document.createElement('div'));
var props = {
position:'fixed', top:'10px', right:'10px', background:'#333', border:'5px solid #333',
color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
fontSize: '11px', whiteSpace: 'nowrap'
}
for (var key in props) { myLog._div.style[key] = props[key]; }
};
if (!myLog._div) { this.createDiv(); }
var logEntry = document.createElement('span');
for (var i=0; i < arguments.length; i++) {
logEntry.innerHTML += this.toJson(arguments[i]) + '<br />';
}
logEntry.innerHTML += '<br />';
myLog._div.appendChild(logEntry);
// Scroll automatically to the bottom
myLog._div.scrollTop = myLog._div.scrollHeight;
}
the simplest idea is to add pkg-config --cflags --libs sdl2 while compiling the code.
g++ file.cpp `pkg-config --cflags --libs sdl2`
An easier way to get the machine epsilon for a given float type is to use np.finfo()
:
print(np.finfo(float).eps)
# 2.22044604925e-16
print(np.finfo(np.float32).eps)
# 1.19209e-07
Or try this one
Second one including second hidden div content to hold the form working and test on fiddle http://jsfiddle.net/7e2XU/21/
<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
<script src="http://twitter.github.com/bootstrap/assets/js/bootstrap-tooltip.js"></script>
<script src="http://twitter.github.com/bootstrap/assets/js/bootstrap-popover.js"></script>
<div id="popover-content" style="display: none" >
<div class="container" style="margin: 25px; ">
<div class="row" style="padding-top: 240px;">
<label id="sample">
<form id="mainForm" name="mainForm" method="post" action="">
<p>
<label>Name :</label>
<input type="text" id="txtName" name="txtName" />
</p>
<p>
<label>Address 1 :</label>
<input type="text" id="txtAddress" name="txtAddress" />
</p>
<p>
<label>City :</label>
<input type="text" id="txtCity" name="txtCity" />
</p>
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>
</label>
</div>
</div>
</div>
<a href="#" style="margin: 40px 40px;" class="btn btn-large btn-primary" rel="popover" data-content='' data-placement="left" data-original-title="Fill in form">Open form</a>
<script>
$('a[rel=popover]').popover({
html: 'true',
placement: 'right',
content : function() {
return $('#popover-content').html();
}
})
</script>
Steven Pribilinskiy's answer drops leading zeroes, for example #ff0000 becomes #ff00.
A solution is to append a leading 0 and substring off the last 2 digits.
var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var hex = '#'+ String('0' + Number(rgb[0]).toString(16)).slice(-2) + String('0' + Number(rgb[1]).toString(16)).slice(-2) + String('0' + Number(rgb[2]).toString(16)).slice(-2);
Note 1:In Drawable folder create test.xml and copy the following code
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke android:width="2dp" />
<gradient
android:angle="90"
android:endColor="#29000000"
android:startColor="#29000000" />
<corners
android:bottomLeftRadius="7dp"
android:bottomRightRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp" />
</shape>
// Note: Corners and shape is as per your requirement.
// Note 2:Create xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/test"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.09"
android:gravity="center"
android:background="@drawable/transperent_shape"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
You could use LINQ, but I would go with RemoveAll
method. I think that is the one that better expresses your intent.
var integers = new List<int> { 1, 2, 3, 4, 5 };
var remove = new List<int> { 1, 3, 5 };
integers.RemoveAll(i => remove.Contains(i));
Without using reversed or [::-1], here is a simple version based on recursion i would consider to be the most readable:
def reverse(s):
if len(s)==2:
return s[-1] + s[0]
if len(s)==1:
return s[0]
return s[-1] + reverse(s[1:len(s)-1]) + s[0]
My answer is similar to Alex's. I'm not sure why React-Router made this so needlessly complicated. Why should I have to wrap my component with a HoC just to get access to what's essentially a global?
Anyway, if you take a look at how they implemented <BrowserRouter>
, it's just a tiny wrapper around history.
We can pull that history bit out so that we can import it from anywhere. The trick, however, is if you're doing server-side rendering and you try to import
the history module, it won't work because it uses browser-only APIs. But that's OK because we usually only redirect in response to a click or some other client-side event. Thus it's probably OK to fake it:
// history.js
if(__SERVER__) {
module.exports = {};
} else {
module.exports = require('history').createBrowserHistory();
}
With the help of webpack, we can define some vars so we know what environment we're in:
plugins: [
new DefinePlugin({
'__SERVER__': 'false',
'__BROWSER__': 'true', // you really only need one of these, but I like to have both
}),
And now you can
import history from './history';
From anywhere. It'll just return an empty module on the server.
If you don't want use these magic vars, you'll just have to require
in the global object where it's needed (inside your event handler). import
won't work because it only works at the top-level.
Java IO using stream oriented APIs is performed using a buffer as temporary storage of data within user space. Data read from disk by DMA is first copied to buffers in kernel space, which is then transfer to buffer in user space. Hence there is overhead. Avoiding it can achieve considerable gain in performance.
We could skip this temporary buffer in user space, if there was a way directly to access the buffer in kernel space. Java NIO provides a way to do so.
ByteBuffer
is among several buffers provided by Java NIO. Its just a container or holding tank to read data from or write data to. Above behavior is achieved by allocating a direct buffer using allocateDirect()
API on Buffer.
Using the equation of the line ab, get the x-coordinate on the line at the same y-coordinate as the point to be sorted.
Check via Google, there are lots of examples, see here for one.
Inlined for ease of viewing:
import win32com.client
def send_mail_via_com(text, subject, recipient, profilename="Outlook2003"):
s = win32com.client.Dispatch("Mapi.Session")
o = win32com.client.Dispatch("Outlook.Application")
s.Logon(profilename)
Msg = o.CreateItem(0)
Msg.To = recipient
Msg.CC = "moreaddresses here"
Msg.BCC = "address"
Msg.Subject = subject
Msg.Body = text
attachment1 = "Path to attachment no. 1"
attachment2 = "Path to attachment no. 2"
Msg.Attachments.Add(attachment1)
Msg.Attachments.Add(attachment2)
Msg.Send()
If you want to add the absent serialVersionUID for a bunch of files, IntelliJ IDEA may not work very well. I come up some simple script to fulfill this goal with ease:
base_dir=$(pwd)
src_dir=$base_dir/src/main/java
ic_api_cp=$base_dir/target/classes
while read f
do
clazz=${f//\//.}
clazz=${clazz/%.java/}
seruidstr=$(serialver -classpath $ic_api_cp $clazz | cut -d ':' -f 2 | sed -e 's/^\s\+//')
perl -ni.bak -e "print $_; printf qq{%s\n}, q{ private $seruidstr} if /public class/" $src_dir/$f
done
You save this script, say as add_serialVersionUID.sh
in your ~/bin
folder. Then you run it in the root directory of your Maven or Gradle project like:
add_serialVersionUID.sh < myJavaToAmend.lst
This .lst includes the list of Java files to add the serialVersionUID in the following format:
com/abc/ic/api/model/domain/item/BizOrderTransDO.java
com/abc/ic/api/model/domain/item/CardPassFeature.java
com/abc/ic/api/model/domain/item/CategoryFeature.java
com/abc/ic/api/model/domain/item/GoodsFeature.java
com/abc/ic/api/model/domain/item/ItemFeature.java
com/abc/ic/api/model/domain/item/ItemPicUrls.java
com/abc/ic/api/model/domain/item/ItemSkuDO.java
com/abc/ic/api/model/domain/serve/ServeCategoryFeature.java
com/abc/ic/api/model/domain/serve/ServeFeature.java
com/abc/ic/api/model/param/depot/DepotItemDTO.java
com/abc/ic/api/model/param/depot/DepotItemQueryDTO.java
com/abc/ic/api/model/param/depot/InDepotDTO.java
com/abc/ic/api/model/param/depot/OutDepotDTO.java
This script uses the JDK serialVer tool. It is ideal for a situation when you want to amend a huge number of classes which had no serialVersionUID set in the first place while maintain the compatibility with the old classes.
The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?
For example, we have i values and get the value of id field
alert(obj[i].id); //works!
But what if we need key with spaces?
In this case, the following construction can help (without point between [] blocks):
alert(obj[i]["No. of interfaces"]); //works too!
It will also complain if the pem file permissions are too open. chmod the file to 600 to fix that.
Your JSON is not correct. Instead of
JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString()); // <-- toString()
parent.put("auth", auth.toString()); // <-- toString()
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
write
JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred);
parent.put("auth", auth);
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
So, the JSONObject.toString() should be called only once for the outer object.
Another thing (most probably not your problem, but I'd like to mention it):
To be sure not to run into encoding problems, you should specify the encoding, if it is not UTF-8
:
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
// ...
OutputStream os = con.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();
The attribute that stores the classes in use is className
.
So you can say:
if (document.body.className.match(/\bmyclass\b/)) {
....
}
If you want a location that shows you how jQuery does everything, I would suggest:
A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =
:
HOME=c
An environment variable is a regular variable that has been marked for export to the environment.
export HOME
HOME=c
You can combine the assignment with the export
statement.
export HOME=c
str.matches(regex)
behaves like Pattern.matches(regex, str)
which attempts to match the entire input sequence against the pattern and returns
true
if, and only if, the entire input sequence matches this matcher's pattern
Whereas matcher.find()
attempts to find the next subsequence of the input sequence that matches the pattern and returns
true
if, and only if, a subsequence of the input sequence matches this matcher's pattern
Thus the problem is with the regex. Try the following.
String test = "User Comments: This is \t a\ta \ntest\n\n message \n";
String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find()); //true
String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2)); //true
Thus in short, the (\\W)*(\\S)*
portion in your first regex matches an empty string as *
means zero or more occurrences and the real matched string is User Comments:
and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W
matches a non word character, ie [^a-zA-Z0-9_]
and the first character is T
, a word character.
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
Stack overflow means exactly that: a stack overflows. Usually there's a one stack in the program that contains local-scope variables and addresses where to return when execution of a routine ends. That stack tends to be a fixed memory range somewhere in the memory, therefore it's limited how much it can contain values.
If the stack is empty you can't pop, if you do you'll get stack underflow error.
If the stack is full you can't push, if you do you'll get stack overflow error.
So stack overflow appears where you allocate too much into the stack. For instance, in the mentioned recursion.
Some implementations optimize out some forms of recursions. Tail recursion in particular. Tail recursive routines are form of routines where the recursive call appears as a final thing what the routine does. Such routine call gets simply reduced into a jump.
Some implementations go so far as implement their own stacks for recursion, therefore they allow the recursion to continue until the system runs out of memory.
Easiest thing you could try would be to increase your stack size if you can. If you can't do that though, the second best thing would be to look whether there's something that clearly causes the stack overflow. Try it by printing something before and after the call into routine. This helps you to find out the failing routine.
Earlier responders have answered the question but have not provided the information the title led me to expect. I had a method that returned a one character string but I wanted a character which I could convert to hexadecimal. The following code demonstrates what I thought I would find in the hope it is helpful to others.
string s = "\ta£\x0394\x221A"; // tab; lower case a; pound sign; Greek delta;
// square root
Debug.Print(s);
char c = s[0];
int i = (int)c;
string x = i.ToString("X");
c = s[1];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[2];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[3];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[4];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
The above code outputs the following to the immediate window:
a£?v
a 97 61
£ 163 A3
? 916 394
v 8730 221A
from within the directory of "my_script.py" you can simply do:
%run ./my_script.py
I use ubuntu 18.04, and it was actually permission issue in my local machine. The issue was gone when I set read/write permission to my .git folder.
Only this worked for me (AndroidX support library):
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null"
android:theme="@style/AppTheme.AppBarOverlay"
android:translationZ="0.1dp"
app:elevation="0dp">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@null"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
This code removes background in all necessary views and also removes shadow from AppBarLayout (which was a problem)
Answer was found here: remove shadow below AppBarLayout widget android
I would recommend doing the following:
foreach ($fields as $key => $field) {
if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
$fields[$key]['value'] = "Some error";
}
}
So basically use $field
when you need the values, and $fields[$key]
when you need to change the data.
First, the replies are correct that what the OP is requesting is a contradiction in terms: virtual methods depend on the run-time type of an instance; static functions specifically don't depend on an instance -- just on a type. That said, it makes sense to have static functions return something specific to a type. For example, I had a family of MouseTool classes for the State pattern and I started having each one have a static function returning the keyboard modifier that went with it; I used those static functions in the factory function that made the correct MouseTool instance. That function checked the mouse state against MouseToolA::keyboardModifier(), MouseToolB::keyboardModifier(), etc. and then instantiated the appropriate one. Of course later I wanted to check if the state was right so I wanted write something like "if (keyboardModifier == dynamic_type(*state)::keyboardModifier())" (not real C++ syntax), which is what this question is asking.
So, if you find yourself wanting this, you may want to rething your solution. Still, I understand the desire to have static methods and then call them dynamically based on the dynamic type of an instance. I think the Visitor Pattern can give you what you want. It gives you what you want. It's a bit of extra code, but it could be useful for other visitors.
See: http://en.wikipedia.org/wiki/Visitor_pattern for background.
struct ObjectVisitor;
struct Object
{
struct TypeInformation;
static TypeInformation GetTypeInformation();
virtual void accept(ObjectVisitor& v);
};
struct SomeObject : public Object
{
static TypeInformation GetTypeInformation();
virtual void accept(ObjectVisitor& v) const;
};
struct AnotherObject : public Object
{
static TypeInformation GetTypeInformation();
virtual void accept(ObjectVisitor& v) const;
};
Then for each concrete Object:
void SomeObject::accept(ObjectVisitor& v) const {
v.visit(*this); // The compiler statically picks the visit method based on *this being a const SomeObject&.
}
void AnotherObject::accept(ObjectVisitor& v) const {
v.visit(*this); // Here *this is a const AnotherObject& at compile time.
}
and then define the base visitor:
struct ObjectVisitor {
virtual ~ObjectVisitor() {}
virtual void visit(const SomeObject& o) {} // Or = 0, depending what you feel like.
virtual void visit(const AnotherObject& o) {} // Or = 0, depending what you feel like.
// More virtual void visit() methods for each Object class.
};
Then the concrete visitor that selects the appropriate static function:
struct ObjectVisitorGetTypeInfo {
Object::TypeInformation result;
virtual void visit(const SomeObject& o) {
result = SomeObject::GetTypeInformation();
}
virtual void visit(const AnotherObject& o) {
result = AnotherObject::GetTypeInformation();
}
// Again, an implementation for each concrete Object.
};
finally, use it:
void printInfo(Object& o) {
ObjectVisitorGetTypeInfo getTypeInfo;
Object::TypeInformation info = o.accept(getTypeInfo).result;
std::cout << info << std::endl;
}
Notes:
If you want to avoid copy-paste errors where one of your visit methods calls the wrong static function, you could use a templated helper function (which can't itself be virtual) t your visitor with a template like this:
struct ObjectVisitorGetTypeInfo {
Object::TypeInformation result;
virtual void visit(const SomeObject& o) { doVisit(o); }
virtual void visit(const AnotherObject& o) { doVisit(o); }
// Again, an implementation for each concrete Object.
private:
template <typename T>
void doVisit(const T& o) {
result = T::GetTypeInformation();
}
};
Update:
As mentioned below, not all implementations support this callback (i.e. platforms like iOS). In this case, as the docs say, you can set the validator explicitly:
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
This works too for .NET Core 2.2, 3.0 and 3.1
Old answer, with more control but may throw PlatformNotSupportedException
:
You can override SSL cert check on a HTTP call with the a anonymous callback function like this
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
using (var client = new HttpClient(httpClientHandler))
{
// Make your request...
}
}
Additionally, I suggest to use a factory pattern for HttpClient
because it is a shared object that might no be disposed immediately and therefore connections will stay open.
torch.Tensor.view()
Simply put, torch.Tensor.view()
which is inspired by numpy.ndarray.reshape()
or numpy.reshape()
, creates a new view of the tensor, as long as the new shape is compatible with the shape of the original tensor.
Let's understand this in detail using a concrete example.
In [43]: t = torch.arange(18)
In [44]: t
Out[44]:
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])
With this tensor t
of shape (18,)
, new views can only be created for the following shapes:
(1, 18)
or equivalently (1, -1)
or (-1, 18)
(2, 9)
or equivalently (2, -1)
or (-1, 9)
(3, 6)
or equivalently (3, -1)
or (-1, 6)
(6, 3)
or equivalently (6, -1)
or (-1, 3)
(9, 2)
or equivalently (9, -1)
or (-1, 2)
(18, 1)
or equivalently (18, -1)
or (-1, 1)
As we can already observe from the above shape tuples, the multiplication of the elements of the shape tuple (e.g. 2*9
, 3*6
etc.) must always be equal to the total number of elements in the original tensor (18
in our example).
Another thing to observe is that we used a -1
in one of the places in each of the shape tuples. By using a -1
, we are being lazy in doing the computation ourselves and rather delegate the task to PyTorch to do calculation of that value for the shape when it creates the new view. One important thing to note is that we can only use a single -1
in the shape tuple. The remaining values should be explicitly supplied by us. Else PyTorch will complain by throwing a RuntimeError
:
RuntimeError: only one dimension can be inferred
So, with all of the above mentioned shapes, PyTorch will always return a new view of the original tensor t
. This basically means that it just changes the stride information of the tensor for each of the new views that are requested.
Below are some examples illustrating how the strides of the tensors are changed with each new view.
# stride of our original tensor `t`
In [53]: t.stride()
Out[53]: (1,)
Now, we will see the strides for the new views:
# shape (1, 18)
In [54]: t1 = t.view(1, -1)
# stride tensor `t1` with shape (1, 18)
In [55]: t1.stride()
Out[55]: (18, 1)
# shape (2, 9)
In [56]: t2 = t.view(2, -1)
# stride of tensor `t2` with shape (2, 9)
In [57]: t2.stride()
Out[57]: (9, 1)
# shape (3, 6)
In [59]: t3 = t.view(3, -1)
# stride of tensor `t3` with shape (3, 6)
In [60]: t3.stride()
Out[60]: (6, 1)
# shape (6, 3)
In [62]: t4 = t.view(6,-1)
# stride of tensor `t4` with shape (6, 3)
In [63]: t4.stride()
Out[63]: (3, 1)
# shape (9, 2)
In [65]: t5 = t.view(9, -1)
# stride of tensor `t5` with shape (9, 2)
In [66]: t5.stride()
Out[66]: (2, 1)
# shape (18, 1)
In [68]: t6 = t.view(18, -1)
# stride of tensor `t6` with shape (18, 1)
In [69]: t6.stride()
Out[69]: (1, 1)
So that's the magic of the view()
function. It just changes the strides of the (original) tensor for each of the new views, as long as the shape of the new view is compatible with the original shape.
Another interesting thing one might observe from the strides tuples is that the value of the element in the 0th position is equal to the value of the element in the 1st position of the shape tuple.
In [74]: t3.shape
Out[74]: torch.Size([3, 6])
|
In [75]: t3.stride() |
Out[75]: (6, 1) |
|_____________|
This is because:
In [76]: t3
Out[76]:
tensor([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17]])
the stride (6, 1)
says that to go from one element to the next element along the 0th dimension, we have to jump or take 6 steps. (i.e. to go from 0
to 6
, one has to take 6 steps.) But to go from one element to the next element in the 1st dimension, we just need only one step (for e.g. to go from 2
to 3
).
Thus, the strides information is at the heart of how the elements are accessed from memory for performing the computation.
This function would return a view and is exactly the same as using torch.Tensor.view()
as long as the new shape is compatible with the shape of the original tensor. Otherwise, it will return a copy.
However, the notes of torch.reshape()
warns that:
contiguous inputs and inputs with compatible strides can be reshaped without copying, but one should not depend on the copying vs. viewing behavior.
So this happened! I accidently clicked on "assume unchanged"! I tried searching on Internet, but could not find any working solution! So, I tried few things here and there and finally I found the solution (easiest one) for this which will undo the assume unchanged!
Right click on "Your Project" then Team > Advanced > No assume Unchanged
.
One problem with .format
is that you lose static type safety. You can have too few arguments for your format, and you can have the wrong types for the format specifiers - both leading to an IllegalFormatException
at runtime, so you might end up with logging code that breaks production.
In contrast, the arguments to +
can be tested by the compiler.
The security history of printf (on which the format
function is modeled) is long and frightening.
You're looking for a response header of Set-Cookie
:
xhr.getResponseHeader('Set-Cookie');
It won't work with HTTPOnly cookies though.
According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2, this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader()
, so the only reason why this could work is basically a "naughty" browser.
This is the only way i could get it working:
JS:
columnDefs: [
{ "width": "100px", "targets": [0] }
]
CSS:
#yourTable{
table-layout: fixed !important;
word-wrap:break-word;
}
The CSS part isn't nice but it does the job.
Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:
CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm
.PHONY: all
all: client
.PHONY: clean
clean:
$(RM) *~ *.o client
OBJECTS=client.o
client: $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)
In the line defining the client target change the order of $(LDFLAGS) as needed.
While you may be able to decompile your APK
file, you will likely hit one big issue:
it's not going to return the code you wrote. It is instead going to return whatever the compiler inlined, with variables given random names, as well as functions given random names. It could take significantly more time to try to decompile and restore it into the code you had, than it will be to start over.
Sadly, things like this have killed many projects.
For the future, I highly recommend learning a Version Control System, like CVS, SVN and git etc.
and how to back it up.
If you have a class like:
public class GenericClass<T> {
private T data;
}
with T
variable, then you can print T
name:
System.out.println(data.getClass().getSimpleName()); // "String", "Integer", etc.
With ES6 arrow functions it will be like this:
//Let's say we have these cars
let cars = [ { brand: 'Porsche', top_speed: 260 },
{ brand: 'Benz', top_speed: 110 },
{ brand: 'Fiat', top_speed: 90 },
{ brand: 'Aston Martin', top_speed: 70 } ]
Array.prototype.sort()
can accept a comparator function (here I used arrow notation, but ordinary functions work the same):
let sortedByBrand = [...cars].sort((first, second) => first.brand > second.brand)
// [ { brand: 'Aston Martin', top_speed: 70 },
// { brand: 'Benz', top_speed: 110 },
// { brand: 'Fiat', top_speed: 90 },
// { brand: 'Porsche', top_speed: 260 } ]
The above approach copies the contents of cars array into a new one and sorts it alphabetically based on brand names. Similarly, you can pass a different function:
let sortedBySpeed =[...cars].sort((first, second) => first.top_speed > second.top_speed)
//[ { brand: 'Aston Martin', top_speed: 70 },
// { brand: 'Fiat', top_speed: 90 },
// { brand: 'Benz', top_speed: 110 },
// { brand: 'Porsche', top_speed: 260 } ]
If you don't mind mutating the orginal array cars.sort(comparatorFunction)
will do the trick.
I experienced the problem mentioned by op
My case was that I was handed an old project and the tests were actually part of the system under test. I assume they were using the external test runner.
this task chain resolved the issue for me
i was able to successfully run the Nunit tests.
You can solve the problem changing the compileSdkVersion in the Grandle.build file from 18 to wtever SDK is installed ..... BUTTTTT
If you are trying to goin back in SDK versions like 18 to 17 ,You can not use the feature available in 18 or 18+
If you are migrating your project (Eclipse to Android Studio ) Then off course you Don't have build.gradle file in your Existed Eclipse project
So, the only solution is to ensure the SDK version installed or not, you are targeting to , If not then install.
Error:Cause: failed to find target with hash string 'android-19' in: C:\Users\setia\AppData\Local\Android\sdk
I also got this error .I was using Text inside body after changing to XML(text/xml) , got result as expected.
If your request is XML Request use XML(text/xml).
If your request is JSON Request use JSON(application/json)
If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.
// form.php
<?php
if (!empty($_POST['submit'])) {
// validate
if ($allGood) {
// put data into database or whatever needs to be done
header('Location: nextpage.php');
exit;
}
}
?>
<form action="form.php">
<input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
...
</form>
This can be made more elegant, but you get the idea...
Also, comments have to be on their own line. They can't be put after an entry. So this won't work:
/node_modules # DON'T COMMENT HERE (since nullifies entire line)
But this will work:
# fine to comment here
/node_modules
When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution
import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])
What you need is a jQuery UI Datepicker
Check out the demo and the source code.
A simple way to see the Git commit short version and the Git commit message is:
git log --oneline
Note that this is shorthand for
git log --pretty=oneline --abbrev-commit
For those using Spring's Java configuration classes, you might write the following:
@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.addAnnotatedClasses(Foo.class);
sessionBuilder.addAnnotatedClasses(Bar.class);
sessionBuilder.addAnnotatedClasses(Bat.class);
return sessionBuilder.buildSessionFactory();
}
You can use httpx
for that.
import httpx
async def get_async(url):
async with httpx.AsyncClient() as client:
return await client.get(url)
urls = ["http://google.com", "http://wikipedia.org"]
# Note that you need an async context to use `await`.
await asyncio.gather(*map(get_async, urls))
if you want a functional syntax, the gamla lib wraps this into get_async
.
Then you can do
await gamla.map(gamla.get_async(10))(["http://google.com", "http://wikipedia.org"])
The 10
is the timeout in seconds.
(disclaimer: I am its author)
i had the same problem... every time that i wanted to publish my css.. I had to make a search/replace.. and relative path wouldnt work either for me because the relative paths were different from dev to production.
Finally was tired of doing the search/replace and I created a dynamic css, (e.g. www.mysite.com/css.php) it's the same but now i could use my php constants in the css. somethig like
.icon{
background-image:url('<?php echo BASE_IMAGE;?>icon.png');
}
and it's not a bad idea to make it dynamic because now i could compress it using YUI compressor without loosing the original format on my dev server.
Good Luck!
Answer 1:
Downloading bootstrap through npm (or bower) permits you to gain some latency time. Instead of getting a remote resource, you get a local one, it's quicker, except if you use a cdn (check below answer)
"npm" was originally to get Node Module, but with the essort of the Javascript language (and the advent of browserify), it has a bit grown up. In fact, you can even download AngularJS on npm, that is not a server side framework. Browserify permits you to use AMD/RequireJS/CommonJS on client side so node modules can be used on client side.
Answer 2:
If you npm install bootstrap (if you dont use a particular grunt or gulp file to move to a dist folder), your bootstrap will be located in "./node_modules/bootstrap/bootstrap.min.css" if I m not wrong.
You can try this:
function in_array_strpos($word, $array){
foreach($array as $a){
if (strpos($word,$a) !== false) {
return true;
}
}
return false;
}
You can use StringUtils
:
import org.apache.commons.lang3.StringUtils;
if (StringUtils.isBlank(str)) {
System.out.println("String is empty");
} else {
System.out.println("String is not empty");
}
Have a look here also: StringUtils.isBlank() vs String.isEmpty()
isBlank
examples:
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
Actually, if you're using AngularJS, you don't need jQuery anymore. AngularJS itself has the binding and directive, which is a very good "replacement" for most things you can do with jQuery.
I usually develop mobile applications using AngularJS and Cordova. The ONLY thing from jQuery I needed is the Selector.
By googling, I see that there is a standalone jQuery selector module out there. It's Sizzle.
And I decided to make a tiny code snippet that help me quickly start a website using AngularJS with the power of jQuery Selector (using Sizzle).
I shared my code here: https://github.com/huytd/Sizzular
You need to set it to C:\Sun\SDK\jdk
(Assuming that is where the JDK is installed - It is not the default) - Do not put the \bin in C:\Sun\SDK\jdk\bin
.
If your app only runs when you are logged in as the current user then put it in the user variables - If it needs to run for all users on your system then put it in System variables.
You might also need to add %JAVA_HOME%\bin
to the path also (Also it depends on whether you run it from just the user or from all users, including System)
<script>_x000D_
myObj = {"key1" : "Hello", "key2" : "Goodbye"};_x000D_
var size = Object.keys(myObj).length;_x000D_
console.log(size);_x000D_
</script>_x000D_
_x000D_
<p id="myObj">The number of <b>keys</b> in <b>myObj</b> are: <script>document.write(size)</script></p>
_x000D_
This works for me:
var size = Object.keys(myObj).length;
I have been practising working on files this evening and realised that I can build on Jochen's answer to provide greater functionality for repeated/multiple use. Unfortunately my answer does not address issue of dealing with large files but does make life easier in smaller files.
with open('filetochange.txt', 'r+') as foo:
data = foo.readlines() #reads file as list
pos = int(input("Which position in list to edit? "))-1 #list position to edit
data.insert(pos, "more foo"+"\n") #inserts before item to edit
x = data[pos+1]
data.remove(x) #removes item to edit
foo.seek(0) #seeks beginning of file
for i in data:
i.strip() #strips "\n" from list items
foo.write(str(i))
I know this question is 4 years old, but I have a couple different options:
tar --to-command grep
The following line will look in example.tgz
for PATTERN
. This is similar to @Jester's example, but I couldn't get his pattern matching to work.
tar xzf example.tgz --to-command 'grep --label="$TAR_FILENAME" -H PATTERN ; true'
tar -tzf
The second option is using tar -tzf
to list the files, then go through them with grep
. You can create a function to use it over and over:
targrep () {
for i in $(tar -tzf "$1"); do
results=$(tar -Oxzf "$1" "$i" | grep --label="$i" -H "$2")
echo "$results"
done
}
Usage:
targrep example.tar.gz "pattern"
Step-by-step:
[newline]ab
ab
[backspace]si
asi
[carriage-return]ha
hai
Carriage return, does not cause a newline. Under some circumstances a single CR or LF may be translated to a CR-LF pair. This is console and/or stream dependent.
Be sure to declare HttpHeaders without null values.
this.http.get('url', {headers: new HttpHeaders({'a': a || '', 'b': b || ''}))
Otherwise, if you try to add a null value to HttpHeaders it will give you an error.
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
There second method will be many times more effective (mostly because of compilers inlining and boxing but still numbers are very expressive):
public static bool CheckObjectImpl(object o)
{
return o != null;
}
public static bool CheckNullableImpl<T>(T? o) where T: struct
{
return o.HasValue;
}
Benchmark test:
BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
[Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
Core : .NET Core 4.6.25009.03, 64bit RyuJIT
Method | Job | Runtime | Mean | Error | StdDev | Min | Max | Median | Rank | Gen 0 | Allocated |
-------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
CheckObject | Clr | Clr | 80.6416 ns | 1.1983 ns | 1.0622 ns | 79.5528 ns | 83.0417 ns | 80.1797 ns | 3 | 0.0060 | 24 B |
CheckNullable | Clr | Clr | 0.0029 ns | 0.0088 ns | 0.0082 ns | 0.0000 ns | 0.0315 ns | 0.0000 ns | 1 | - | 0 B |
CheckObject | Core | Core | 77.2614 ns | 0.5703 ns | 0.4763 ns | 76.4205 ns | 77.9400 ns | 77.3586 ns | 2 | 0.0060 | 24 B |
CheckNullable | Core | Core | 0.0007 ns | 0.0021 ns | 0.0016 ns | 0.0000 ns | 0.0054 ns | 0.0000 ns | 1 | - | 0 B |
Benchmark code:
public class BenchmarkNullableCheck
{
static int? x = (new Random()).Next();
public static bool CheckObjectImpl(object o)
{
return o != null;
}
public static bool CheckNullableImpl<T>(T? o) where T: struct
{
return o.HasValue;
}
[Benchmark]
public bool CheckObject()
{
return CheckObjectImpl(x);
}
[Benchmark]
public bool CheckNullable()
{
return CheckNullableImpl(x);
}
}
https://github.com/dotnet/BenchmarkDotNet was used
So if you have an option (e.g. writing custom serializers) to process Nullable in different pipeline than object
- and use their specific properties - do it and use Nullable specific properties.
So from consistent thinking point of view HasValue
should be preferred. Consistent thinking can help you to write better code do not spending too much time in details.
PS. People say that advice "prefer HasValue because of consistent thinking" is not related and useless. Can you predict the performance of this?
public static bool CheckNullableGenericImpl<T>(T? t) where T: struct
{
return t != null; // or t.HasValue?
}
PPS People continue minus, seems nobody tries to predict performance of CheckNullableGenericImpl
. I will tell you: there compiler will not help you replacing !=null
with HasValue
. HasValue
should be used directly if you are interested in performance.
From: http://nginx.org/r/large_client_header_buffers
Syntax:
large_client_header_buffers
number
size
;
Default:large_client_header_buffers 4 8k;
Context: http, serverSets the maximum
number
andsize
of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.
so you need to change the size parameter at the end of that line to something bigger for your needs.
"Z" doesn't stand for "Zulu"
I don't have any more information than the Wikipedia article cited by the two existing answers, but I believe the interpretation that "Z" stands for "Zulu" is incorrect. UTC time is referred to as "Zulu time" because of the use of Z to identify it, not the other way around. The "Z" seems to have been used to mark the time zone as the "zero zone", in which case "Z" unsurprisingly stands for "zero" (assuming the following information from Wikipedia is accurate):
Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications — zones M and Y have the same clock time but differ by 24 hours: a full day). These can be vocalized using the NATO phonetic alphabet which pronounces the letter Z as Zulu, leading to the use of the term "Zulu Time" for Greenwich Mean Time, or UT1 from January 1, 1972 onward.
As @letitbee said, its best practice to assign primary keys to tables and properly define the relationships to allow for proper ORM querying. That being said...
If you're interested in writing a query along the lines of:
SELECT
user.email,
user.name,
document.name,
documents_permissions.readAllowed,
documents_permissions.writeAllowed
FROM
user, document, documents_permissions
WHERE
user.email = "[email protected]";
Then you should go for something like:
session.query(
User,
Document,
DocumentsPermissions
).filter(
User.email == Document.author
).filter(
Document.name == DocumentsPermissions.document
).filter(
User.email == "[email protected]"
).all()
If instead, you want to do something like:
SELECT 'all the columns'
FROM user
JOIN document ON document.author_id = user.id AND document.author == User.email
JOIN document_permissions ON document_permissions.document_id = document.id AND document_permissions.document = document.name
Then you should do something along the lines of:
session.query(
User
).join(
Document
).join(
DocumentsPermissions
).filter(
User.email == "[email protected]"
).all()
One note about that...
query.join(Address, User.id==Address.user_id) # explicit condition
query.join(User.addresses) # specify relationship from left to right
query.join(Address, User.addresses) # same, with explicit target
query.join('addresses') # same, using a string
For more information, visit the docs.
The spring data JPA query needs the "%" chars as well as a space char following like
in your query, as in
@Query("Select c from Registration c where c.place like %:place%")
.
Cf. http://docs.spring.io/spring-data/jpa/docs/current/reference/html.
You may want to get rid of the @Query
annotation alltogether, as it seems to resemble the standard query (automatically implemented by the spring data proxies); i.e. using the single line
List<Registration> findByPlaceContaining(String place);
is sufficient.
They're not actually characters, they're hexadecimal digits.
You can use strip binary on object file(eg. executable) to strip all symbols from it.
Note: it changes file itself and don't create copy.
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
I put together a little C program to print out the current timestamp (locale-safe, no bad characters...). Then, I use the FOR command to save the result in an environment variable:
:: Get the timestamp
for /f %%x in ('@timestamp') do set TIMESTAMP=%%x
:: Use it to generate a filename
for /r %%x in (.\processed\*) do move "%%~x" ".\archived\%%~nx-%TIMESTAMP%%%~xx"
Here's a link:
$('#txtSearchProdAssign').keypress(function (e) {
if (e.which == 13) {
$('input[name = butAssignProd]').click();
return false;
}
});
I also just found Submitting a form on 'Enter' which covers most of the issues comprehensively.
My 2 Cents:
Choice 1: Add a breakpoint at the end of main()
Choice 2: Add this code, right before the return 0;
:
std::cout << "Press ENTER to continue..."; //So the User knows what to do
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You need to include <iomanip>
for std::numeric_limits
Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.
thread apply all bt
I had this issue when I deleted a project and tried to import the code again. Eclipse never really deleted the project and still held a reference to the project name/folder in the workspace. I had to created a new project with the same name and my code appeared as it was. I believe this only worked because the project path was never changed.
Bootstrap 3 with DataTables Example: Bootstrap Docs & DataTables Docs
$(document).ready(function() {
$('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap.min.css rel=stylesheet><div class=container><h1>Bootstrap 3 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap.min.js></script>
_x000D_
Bootstrap 4 with DataTables Example: Bootstrap Docs & DataTables Docs
$(document).ready(function() {
$('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap4.min.css rel=stylesheet><div class=container><h1>Bootstrap 4 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-inverse table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tfoot><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>61<td>2011/04/25<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>63<td>2011/07/25<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>66<td>2009/01/12<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>22<td>2012/03/29<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>33<td>2008/11/28<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>61<td>2012/12/02<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>59<td>2012/08/06<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>55<td>2010/10/14<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>39<td>2009/09/15<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>23<td>2008/12/13<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>30<td>2008/12/19<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>22<td>2013/03/03<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>36<td>2008/10/16<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>43<td>2012/12/18<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>19<td>2010/03/17<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>66<td>2012/11/27<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>64<td>2010/06/09<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>59<td>2009/04/10<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>41<td>2012/10/13<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>35<td>2012/09/26<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>30<td>2011/09/03<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>40<td>2009/06/25<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>21<td>2011/12/12<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>23<td>2010/09/20<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>47<td>2009/10/09<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>42<td>2010/12/22<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>28<td>2010/11/14<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>28<td>2011/06/07<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>48<td>2010/03/11<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>20<td>2011/08/14<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>37<td>2011/06/02<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>53<td>2009/10/22<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>27<td>2011/05/07<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>22<td>2008/10/26<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>46<td>2011/03/09<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>47<td>2009/12/09<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>51<td>2008/12/16<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>41<td>2010/02/12<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>62<td>2009/02/14<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>37<td>2008/12/11<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>65<td>2008/09/26<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>64<td>2011/02/03<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>38<td>2011/05/03<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>37<td>2009/08/19<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>61<td>2013/08/11<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>47<td>2009/07/07<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>64<td>2012/04/09<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>63<td>2010/01/04<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>56<td>2012/06/01<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>43<td>2013/02/01<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>46<td>2011/12/06<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>47<td>2011/03/21<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>21<td>2009/02/27<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>30<td>2010/07/14<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>51<td>2008/11/13<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>29<td>2011/06/27<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>27<td>2011/01/25<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap4.min.js></script>
_x000D_
Bootstrap 3 with Bootstrap Table Example: Bootstrap Docs & Bootstrap Table Docs
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.css rel=stylesheet><table data-sort-name=stargazers_count data-sort-order=desc data-toggle=table data-url="https://api.github.com/users/wenzhixin/repos?type=owner&sort=full_name&direction=asc&per_page=100&page=1"><thead><tr><th data-field=name data-sortable=true>Name<th data-field=stargazers_count data-sortable=true>Stars<th data-field=forks_count data-sortable=true>Forks<th data-field=description data-sortable=true>Description</thead></table><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.js></script>
_x000D_
Bootstrap 3 with Bootstrap Sortable Example: Bootstrap Docs & Bootstrap Sortable Docs
function randomDate(t,e){return new Date(t.getTime()+Math.random()*(e.getTime()-t.getTime()))}function randomName(){return["Jack","Peter","Frank","Steven"][Math.floor(4*Math.random())]+" "+["White","Jackson","Sinatra","Spielberg"][Math.floor(4*Math.random())]}function newTableRow(){var t=moment(randomDate(new Date(2e3,0,1),new Date)).format("D.M.YYYY"),e=Math.round(Math.random()*Math.random()*100*100)/100,a=Math.round(Math.random()*Math.random()*100*100)/100,r=Math.round(Math.random()*Math.random()*100*100)/100;return"<tr><td>"+randomName()+"</td><td>"+e+"</td><td>"+a+"</td><td>"+r+"</td><td>"+Math.round(100*(e+a+r))/100+"</td><td data-dateformat='D-M-YYYY'>"+t+"</td></tr>"}function customSort(){alert("Custom sort.")}!function(t,e){"use strict";"function"==typeof define&&define.amd?define("tinysort",function(){return e}):t.tinysort=e}(this,function(){"use strict";function t(t,e){for(var a,r=t.length,o=r;o--;)e(t[a=r-o-1],a)}function e(t,e,a){for(var o in e)(a||t[o]===r)&&(t[o]=e[o]);return t}function a(t,e,a){u.push({prepare:t,sort:e,sortBy:a})}var r,o=!1,n=null,s=window,d=s.document,i=parseFloat,l=/(-?\d+\.?\d*)\s*$/g,c=/(\d+\.?\d*)\s*$/g,u=[],f=0,h=0,p=String.fromCharCode(4095),m={selector:n,order:"asc",attr:n,data:n,useVal:o,place:"org",returns:o,cases:o,natural:o,forceStrings:o,ignoreDashes:o,sortFunction:n,useFlex:o,emptyEnd:o};return s.Element&&function(t){t.matchesSelector=t.matchesSelector||t.mozMatchesSelector||t.msMatchesSelector||t.oMatchesSelector||t.webkitMatchesSelector||function(t){for(var e=this,a=(e.parentNode||e.document).querySelectorAll(t),r=-1;a[++r]&&a[r]!=e;);return!!a[r]}}(Element.prototype),e(a,{loop:t}),e(function(a,s){function v(t){var a=!!t.selector,r=a&&":"===t.selector[0],o=e(t||{},m);E.push(e({hasSelector:a,hasAttr:!(o.attr===n||""===o.attr),hasData:o.data!==n,hasFilter:r,sortReturnNumber:"asc"===o.order?1:-1},o))}function b(t,e,a){for(var r=a(t.toString()),o=a(e.toString()),n=0;r[n]&&o[n];n++)if(r[n]!==o[n]){var s=Number(r[n]),d=Number(o[n]);return s==r[n]&&d==o[n]?s-d:r[n]>o[n]?1:-1}return r.length-o.length}function g(t){for(var e,a,r=[],o=0,n=-1,s=0;e=(a=t.charAt(o++)).charCodeAt(0);){var d=46==e||e>=48&&57>=e;d!==s&&(r[++n]="",s=d),r[n]+=a}return r}function w(){return Y.forEach(function(t){F.appendChild(t.elm)}),F}function S(t){var e=t.elm,a=d.createElement("div");return t.ghost=a,e.parentNode.insertBefore(a,e),t}function y(t,e){var a=t.ghost,r=a.parentNode;r.insertBefore(e,a),r.removeChild(a),delete t.ghost}function C(t,e){var a,r=t.elm;return e.selector&&(e.hasFilter?r.matchesSelector(e.selector)||(r=n):r=r.querySelector(e.selector)),e.hasAttr?a=r.getAttribute(e.attr):e.useVal?a=r.value||r.getAttribute("value"):e.hasData?a=r.getAttribute("data-"+e.data):r&&(a=r.textContent),M(a)&&(e.cases||(a=a.toLowerCase()),a=a.replace(/\s+/g," ")),null===a&&(a=p),a}function M(t){return"string"==typeof t}M(a)&&(a=d.querySelectorAll(a)),0===a.length&&console.warn("No elements to sort");var x,N,F=d.createDocumentFragment(),D=[],Y=[],$=[],E=[],k=!0,A=a.length&&a[0].parentNode,T=A.rootNode!==document,R=a.length&&(s===r||!1!==s.useFlex)&&!T&&-1!==getComputedStyle(A,null).display.indexOf("flex");return function(){0===arguments.length?v({}):t(arguments,function(t){v(M(t)?{selector:t}:t)}),f=E.length}.apply(n,Array.prototype.slice.call(arguments,1)),t(a,function(t,e){N?N!==t.parentNode&&(k=!1):N=t.parentNode;var a=E[0],r=a.hasFilter,o=a.selector,n=!o||r&&t.matchesSelector(o)||o&&t.querySelector(o)?Y:$,s={elm:t,pos:e,posn:n.length};D.push(s),n.push(s)}),x=Y.slice(0),Y.sort(function(e,a){var n=0;for(0!==h&&(h=0);0===n&&f>h;){var s=E[h],d=s.ignoreDashes?c:l;if(t(u,function(t){var e=t.prepare;e&&e(s)}),s.sortFunction)n=s.sortFunction(e,a);else if("rand"==s.order)n=Math.random()<.5?1:-1;else{var p=o,m=C(e,s),v=C(a,s),w=""===m||m===r,S=""===v||v===r;if(m===v)n=0;else if(s.emptyEnd&&(w||S))n=w&&S?0:w?1:-1;else{if(!s.forceStrings){var y=M(m)?m&&m.match(d):o,x=M(v)?v&&v.match(d):o;y&&x&&m.substr(0,m.length-y[0].length)==v.substr(0,v.length-x[0].length)&&(p=!o,m=i(y[0]),v=i(x[0]))}n=m===r||v===r?0:s.natural&&(isNaN(m)||isNaN(v))?b(m,v,g):v>m?-1:m>v?1:0}}t(u,function(t){var e=t.sort;e&&(n=e(s,p,m,v,n))}),0==(n*=s.sortReturnNumber)&&h++}return 0===n&&(n=e.pos>a.pos?1:-1),n}),function(){var t=Y.length===D.length;if(k&&t)R?Y.forEach(function(t,e){t.elm.style.order=e}):N?N.appendChild(w()):console.warn("parentNode has been removed");else{var e=E[0].place,a="start"===e,r="end"===e,o="first"===e,n="last"===e;if("org"===e)Y.forEach(S),Y.forEach(function(t,e){y(x[e],t.elm)});else if(a||r){var s=x[a?0:x.length-1],d=s&&s.elm.parentNode,i=d&&(a&&d.firstChild||d.lastChild);i&&(i!==s.elm&&(s={elm:i}),S(s),r&&d.appendChild(s.ghost),y(s,w()))}else(o||n)&&y(S(x[o?0:x.length-1]),w())}}(),Y.map(function(t){return t.elm})},{plugin:a,defaults:m})}()),function(t,e){"function"==typeof define&&define.amd?define(["jquery","tinysort","moment"],e):e(t.jQuery,t.tinysort,t.moment||void 0)}(this,function(t,e,a){var r,o,n,s=t(document);function d(e){var s=void 0!==a;r=e.sign?e.sign:"arrow","default"==e.customSort&&(e.customSort=c),o=e.customSort||o||c,n=e.emptyEnd,t("table.sortable").each(function(){var r=t(this),o=!0===e.applyLast;r.find("span.sign").remove(),r.find("> thead [colspan]").each(function(){for(var e=parseFloat(t(this).attr("colspan")),a=1;a<e;a++)t(this).after('<th class="colspan-compensate">')}),r.find("> thead [rowspan]").each(function(){for(var e=t(this),a=parseFloat(e.attr("rowspan")),r=1;r<a;r++){var o=e.parent("tr"),n=o.next("tr"),s=o.children().index(e);n.children().eq(s).before('<th class="rowspan-compensate">')}}),r.find("> thead tr").each(function(e){t(this).find("th").each(function(a){var r=t(this);r.addClass("nosort").removeClass("up down"),r.attr("data-sortcolumn",a),r.attr("data-sortkey",a+"-"+e)})}),r.find("> thead .rowspan-compensate, .colspan-compensate").remove(),r.find("th").each(function(){var e=t(this);if(void 0!==e.attr("data-dateformat")&&s){var o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var r=t(this);r.attr("data-value",a(r.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss"))})}else if(void 0!==e.attr("data-valueprovider")){o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var a=t(this);a.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(a.text())[0])})}}),r.find("td").each(function(){var e=t(this);void 0!==e.attr("data-dateformat")&&s?e.attr("data-value",a(e.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss")):void 0!==e.attr("data-valueprovider")?e.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(e.text())[0]):void 0===e.attr("data-value")&&e.attr("data-value",e.text())});var n=l(r),d=n.bsSort;r.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var a=t(this),r=a.closest("table.sortable");a.data("sortTable",r);var s=a.attr("data-sortkey"),i=o?n.lastSort:-1;d[s]=o?d[s]:a.attr("data-defaultsort"),void 0!==d[s]&&o===(s===i)&&(d[s]="asc"===d[s]?"desc":"asc",u(a,r))})})}function i(e){var a=t(e),r=a.data("sortTable")||a.closest("table.sortable");u(a,r)}function l(e){var a=e.data("bootstrap-sortable-context");return void 0===a&&(a={bsSort:[],lastSort:void 0},e.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var r=t(this),o=r.attr("data-sortkey");a.bsSort[o]=r.attr("data-defaultsort"),void 0!==a.bsSort[o]&&(a.lastSort=o)}),e.data("bootstrap-sortable-context",a)),a}function c(t,a){e(t,a)}function u(e,a){a.trigger("before-sort");var s=parseFloat(e.attr("data-sortcolumn")),d=l(a),i=d.bsSort;if(e.attr("colspan")){var c=parseFloat(e.data("mainsort"))||0,f=parseFloat(e.data("sortkey").split("-").pop());if(a.find("> thead tr").length-1>f)return void u(a.find('[data-sortkey="'+(s+c)+"-"+(f+1)+'"]'),a);s+=c}var h=e.attr("data-defaultsign")||r;if(a.find("> thead th").each(function(){t(this).removeClass("up").removeClass("down").addClass("nosort")}),t.browser.mozilla){var p=a.find("> thead div.mozilla");void 0!==p&&(p.find(".sign").remove(),p.parent().html(p.html())),e.wrapInner('<div class="mozilla"></div>'),e.children().eq(0).append('<span class="sign '+h+'"></span>')}else a.find("> thead span.sign").remove(),e.append('<span class="sign '+h+'"></span>');var m=e.attr("data-sortkey"),v="desc"!==e.attr("data-firstsort")?"desc":"asc",b=i[m]||v;d.lastSort!==m&&void 0!==i[m]||(b="asc"===b?"desc":"asc"),i[m]=b,d.lastSort=m,"desc"===i[m]?(e.find("span.sign").addClass("up"),e.addClass("up").removeClass("down nosort")):e.addClass("down").removeClass("up nosort");var g=a.children("tbody").children("tr"),w=[];t(g.filter('[data-disablesort="true"]').get().reverse()).each(function(e,a){var r=t(a);w.push({index:g.index(r),row:r}),r.remove()});var S=g.not('[data-disablesort="true"]');if(0!=S.length){var y="asc"===i[m]&&n;o(S,{emptyEnd:y,selector:"td:nth-child("+(s+1)+")",order:i[m],data:"value"})}t(w.reverse()).each(function(t,e){0===e.index?a.children("tbody").prepend(e.row):a.children("tbody").children("tr").eq(e.index-1).after(e.row)}),a.find("> tbody > tr > td.sorted,> thead th.sorted").removeClass("sorted"),S.find("td:eq("+s+")").addClass("sorted"),e.addClass("sorted"),a.trigger("sorted")}if(t.bootstrapSortable=function(t){null==t?d({}):t.constructor===Boolean?d({applyLast:t}):void 0!==t.sortingHeader?i(t.sortingHeader):d(t)},s.on("click",'table.sortable>thead th[data-defaultsort!="disabled"]',function(t){i(this)}),!t.browser){t.browser={chrome:!1,mozilla:!1,opera:!1,msie:!1,safari:!1};var f=navigator.userAgent;t.each(t.browser,function(e){t.browser[e]=!!new RegExp(e,"i").test(f),t.browser.mozilla&&"mozilla"===e&&(t.browser.mozilla=!!new RegExp("firefox","i").test(f)),t.browser.chrome&&"safari"===e&&(t.browser.safari=!1)})}t(t.bootstrapSortable)}),function(){var t=$("table");t.append(newTableRow()),t.append(newTableRow()),$("button.add-row").on("click",function(){var e=$(this);t.append(newTableRow()),e.data("sort")?$.bootstrapSortable(!0):$.bootstrapSortable(!1)}),$("button.change-sort").on("click",function(){$(this).data("custom")?$.bootstrapSortable(!0,void 0,customSort):$.bootstrapSortable(!0,void 0,"default")}),t.on("sorted",function(){alert("Table was sorted.")}),$("#event").on("change",function(){$(this).is(":checked")?t.on("sorted",function(){alert("Table was sorted.")}):t.off("sorted")}),$("input[name=sign]:radio").change(function(){$.bootstrapSortable(!0,$(this).val())})}();
_x000D_
table.sortable span.sign { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th:after { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th.arrow:after { content: ''; } table.sortable span.arrow, span.reversed, th.arrow.down:after, th.reversedarrow.down:after, th.arrow.up:after, th.reversedarrow.up:after { border-style: solid; border-width: 5px; font-size: 0; border-color: #ccc transparent transparent transparent; line-height: 0; height: 0; width: 0; margin-top: -2px; } table.sortable span.arrow.up, th.arrow.up:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed, th.reversedarrow.down:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed.up, th.reversedarrow.up:after { border-color: #ccc transparent transparent transparent; margin-top: -2px; } table.sortable span.az:before, th.az.down:after { content: "a .. z"; } table.sortable span.az.up:before, th.az.up:after { content: "z .. a"; } table.sortable th.az.nosort:after, th.AZ.nosort:after, th._19.nosort:after, th.month.nosort:after { content: ".."; } table.sortable span.AZ:before, th.AZ.down:after { content: "A .. Z"; } table.sortable span.AZ.up:before, th.AZ.up:after { content: "Z .. A"; } table.sortable span._19:before, th._19.down:after { content: "1 .. 9"; } table.sortable span._19.up:before, th._19.up:after { content: "9 .. 1"; } table.sortable span.month:before, th.month.down:after { content: "jan .. dec"; } table.sortable span.month.up:before, th.month.up:after { content: "dec .. jan"; } table.sortable thead th:not([data-defaultsort=disabled]) { cursor: pointer; position: relative; top: 0; left: 0; } table.sortable thead th:hover:not([data-defaultsort=disabled]) { background: #efefef; } table.sortable thead th div.mozilla { position: relative; }
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css rel=stylesheet><link href=https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><div class=container><div class=hero-unit><h1>Bootstrap Sortable</h1></div><table class="sortable table table-bordered table-striped"><thead><tr><th style=width:20%;vertical-align:middle data-defaultsign=nospan class=az data-defaultsort=asc rowspan=2><i class="fa fa-fw fa-map-marker"></i>Name<th style=text-align:center colspan=4 data-mainsort=3>Results<th data-defaultsort=disabled><tr><th style=width:20% colspan=2 data-mainsort=1 data-firstsort=desc>Round 1<th style=width:20%>Round 2<th style=width:20%>Total<t
Solution
Try this: x <- read.csv("C:/Users/surfcat/Desktop/2006_dissimilarity.csv", header=TRUE)
Explanation
R is not able to understand normal windows paths correctly because the "\"
has special meaning - it is used as escape character to give following characters special meaning (\n
for newline, \t
for tab, \r
for carriage return, ..., have a look here ).
Because R does not know the sequence \U
it complains. Just replace the "\"
with "/"
or use an additional "\"
to escape the "\"
from its special meaning and everything works smooth.
Alternative
On windows, I think the best thing to do to improve your workflow with windows specific paths in R is to use e.g. AutoHotkey which allows for custom hotkeys:
AutoHotkey Code Snippet (link to homepage)
^+v::
StringReplace, clipboard, clipboard, \, /, All
SendInput, %clipboard%
Sadly, I think that JSTL doesn't support anything but an iteration through all elements to figure this out. In the past, I've used the forEach method in the core tag library:
<c:set var="contains" value="false" />
<c:forEach var="item" items="${myList}">
<c:if test="${item eq myValue}">
<c:set var="contains" value="true" />
</c:if>
</c:forEach>
After this runs, ${contains} will be equal to "true" if myList contained myValue.
Depends on what you call "best." From a theoretical point of view, you cannot solve the problem in less than O(n)
in a deterministic Turing machine.
The naive algorithm is too loop and update min, max. However, a recursive solution will require less comparisons than naive algorithm, if you want to get min, max simultaneously (it isn't necessarily faster due to function call overhead).
struct MinMax{
public int Min,Max;
}
MinMax FindMinMax(int[] array, int start, int end) {
if (start == end)
return new MinMax { Min = array[start], Max = array[start] };
if (start == end - 1)
return new MinMax { Min = Math.Min(array[start], array[end]), Max = Math.Max(array[start], array[end]) } ;
MinMax res1 = FindMinMax(array, start, (start + end)/2);
MinMax res2 = FindMinMax(array, (start+end)/2+1, end);
return new MinMax { Min = Math.Min(res1.Min, res2.Min), Max = Math.Max(res1.Max, res2.Max) } ;
}
The simplest solution would be to sort and get the first and last item, though it's obviously not the fastest ;)
The best solution, performance-wise, to find the minimum or maximum is the naive algorithm you written (with a single loop).
THIS IS JUST A NOTE FOR ANYONE DEALING WITH THIS PROBLEM USING THE RUBY DRIVER
I had this same problem when using the Ruby Gem.
To set slaveOk in Ruby, you just pass it as an argument when you create the client like this:
mongo_client = MongoClient.new("localhost", 27017, { slave_ok: true })
https://github.com/mongodb/mongo-ruby-driver/wiki/Tutorial#making-a-connection
mongo_client = MongoClient.new # (optional host/port args)
Notice that 'args' is the third optional argument.
Also, take a look at FrameLayout
, that's how the Camera's Gallery application implements the Zoom buttons overlay.
I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on
git branch -f <branchname> <commit>
Here is a scenario where I have needed to do this.
Develop on the wrong branch and hence need to reset it.
Cleanly develop and release some software.
Mistake: Accidentally stay on the release branch while developing further.
"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.
Create a branch for the development that is up to date holding the work committed so far and switch to it.
git branch development
git checkout development
Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.
Correct the release branch to point back to the last real release.
git branch -f release release2
The release branch is now correct again, like this ...
git push -f <remote> <branch>
is well described in another thread, though the word "overwrite" in the title is misleading.
Force "git push" to overwrite remote files
pure javascript no jQuery
function sah() {_x000D_
$("#div2").attr("disabled", "disabled").off('click');_x000D_
var x1=$("#div2").hasClass("disabledDiv");_x000D_
_x000D_
(x1==true)?$("#div2").removeClass("disabledDiv"):$("#div2").addClass("disabledDiv");_x000D_
sah1(document.getElementById("div1"));_x000D_
_x000D_
}_x000D_
_x000D_
function sah1(el) {_x000D_
try {_x000D_
el.disabled = el.disabled ? false : true;_x000D_
} catch (E) {}_x000D_
if (el.childNodes && el.childNodes.length > 0) {_x000D_
for (var x = 0; x < el.childNodes.length; x++) {_x000D_
sah1(el.childNodes[x]);_x000D_
}_x000D_
}_x000D_
}
_x000D_
#div2{_x000D_
padding:5px 10px;_x000D_
background-color:#777;_x000D_
width:150px;_x000D_
margin-bottom:20px;_x000D_
}_x000D_
.disabledDiv {_x000D_
pointer-events: none;_x000D_
opacity: 0.4;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="div1">_x000D_
<div id="div2" onclick="alert('Hello')">Click me</div>_x000D_
<input type="text" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="button" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="radio" name="sex" value="Male" />Male_x000D_
<Br />_x000D_
<input type="radio" name="sex" value="Female" />Female_x000D_
<Br />_x000D_
</div>_x000D_
<Br />_x000D_
<Br />_x000D_
<input type="button" value="Click" onclick="sah()" />
_x000D_
I've created a tool called Rector, that handles instant upgrades. There is also mysql ? mysqli set.
It handles:
function renaming
constant renaming
switched arguments
non-1:1 function calls changes, e.g.
$data = mysql_db_name($result, $row);
?
mysqli_data_seek($result, $row);
$fetch = mysql_fetch_row($result);
$data = $fetch[0];
composer require rector/rector --dev
// or in case of composer conflicts
composer require rector/rector-prefixed --dev
rector.php
in project root directory with the Mysql to Mysqli set<?php
use Rector\Core\Configuration\Option;
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$parameters->set(Option::SETS, [
SetList::MYSQL_TO_MYSQLI,
]);
};
vendor/bin/rector process src --dry-run
vendor/bin/rector process src
I've already run it on 2 big PHP projects and it works perfectly.
I ran into a problem where the browser refused to serve up content that it had retrieved when the request passed in cookies (e.g., the xhr had its withCredentials=true
), and the site had Access-Control-Allow-Origin
set to *
. (The error in Chrome was, "Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.")
Building on the answer from @jgauffin, I created this, which is basically a way of working around that particular browser security check, so caveat emptor.
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// We'd normally just use "*" for the allow-origin header,
// but Chrome (and perhaps others) won't allow you to use authentication if
// the header is set to "*".
// TODO: Check elsewhere to see if the origin is actually on the list of trusted domains.
var ctx = filterContext.RequestContext.HttpContext;
var origin = ctx.Request.Headers["Origin"];
var allowOrigin = !string.IsNullOrWhiteSpace(origin) ? origin : "*";
ctx.Response.AddHeader("Access-Control-Allow-Origin", allowOrigin);
ctx.Response.AddHeader("Access-Control-Allow-Headers", "*");
ctx.Response.AddHeader("Access-Control-Allow-Credentials", "true");
base.OnActionExecuting(filterContext);
}
}
If you want to be really efficient and you have enough time to spent, use SIMD instruction.
You can compare several pairs in one instruction:
r0 := min(a0, b0)
r1 := min(a1, b1)
r2 := min(a2, b2)
r3 := min(a3, b3)
__m64 _mm_min_pu8(__m64 a , __m64 b );
Today every computer supports it. Other already have written min function for you:
http://smartdata.usbid.com/datasheets/usbid/2001/2001-q1/i_minmax.pdf
or use already ready library.
Try
//*[text()='qwerty']
because .
is your current element
There's no need for hacks or overflow. There's a pseudo-element for the dropdown arrow on IE:
select::-ms-expand {
display: none;
}
I tried installing the module locally with version and it worked!!
npm install request@^2.*
Thanks.
You need J-query library to do this simply:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
First you need to put your element in div like this:
<div id="divClickHere">
<a id="a_tbnotesverbergen" href="#nothing">click here</a>
</div>
Then you should write this J-Query Code:
<script type="text/javascript">
$(document).ready(function(){
$("#a_tbnotesverbergen").click(function(){
$("#divClickHere a").text('Your new text');
});
});
</script>
Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:
SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
return *this;
}
I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).
As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.
You can create your own custom validation method using the addMethod
function. Say you wanted to validate "dd/mm/yyyy":
$.validator.addMethod(
"australianDate",
function(value, element) {
// put your own logic here, this is just a (crappy) example
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy."
);
And then on your form add:
$('#myForm')
.validate({
rules : {
myDate : {
australianDate : true
}
}
})
;
function closeWin() // Tested Code
{
var someIframe = window.parent.document.getElementById('iframe_callback');
someIframe.parentNode.removeChild(window.parent.document.getElementById('iframe_callback'));
}
<input class="question" name="Close" type="button" value="Close" onClick="closeWin()" tabindex="10" />
This can also be done with the Image
class of the PIL library:
from PIL import Image
import numpy as np
im_frame = Image.open(path_to_file + 'file.png')
np_frame = np.array(im_frame.getdata())
Note: The .getdata()
might not be needed - np.array(im_frame)
should also work
It should work fine. Don't use tuple
, list
or other special names as a variable name. It's probably what's causing your problem.
>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)
>>> tuple = 'whoops' # Don't do this
>>> tuple(l)
TypeError: 'tuple' object is not callable
Add intl
package to your pubspec.yaml
file.
import 'package:intl/intl.dart';
DateFormat dateFormat = DateFormat("yyyy-MM-dd HH:mm:ss");
Converting DateTime object to String
String string = dateFormat.format(DateTime.now());
Converting String to DateTime object
DateTime dateTime = dateFormat.parse("2019-07-19 8:40:23");
Just to elaborate on Bhavin's excellent answer - editing the solution file works but you may still get the incompatible error (as David reported) if you had .NET 4.5 selected as the default .NET version in your VS2012 project and your VS2010 enviroment doesn't support that.
To quickly fix that, open the VS2012 .csproj file in a text editor and change the TargetFrameworkVersion down to 4.0 (from 4.5). VS2010 will then happily load the "edited" solution and projects.
You'll also have to edit an app.config files that have references to .NET 4.5 in a similar way to allow them to run on a .NET 4.0 environment.
when random_state set to an integer, train_test_split will return same results for each execution.
when random_state set to an None, train_test_split will return different results for each execution.
see below example:
from sklearn.model_selection import train_test_split
X_data = range(10)
y_data = range(10)
for i in range(5):
X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size = 0.3,random_state = 0) # zero or any other integer
print(y_test)
print("*"*30)
for i in range(5):
X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size = 0.3,random_state = None)
print(y_test)
Output:
[2, 8, 4]
[2, 8, 4]
[2, 8, 4]
[2, 8, 4]
[2, 8, 4]
[4, 7, 6]
[4, 3, 7]
[8, 1, 4]
[9, 5, 8]
[6, 4, 5]
These are really two questions.
The first one is answered here: Calling a Sub in VBA
To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.
You need to do this in transaction to ensure two simultaneous clients won't insert same fieldValue twice:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
DECLARE @id AS INT
SELECT @id = tableId FROM table WHERE fieldValue=@newValue
IF @id IS NULL
BEGIN
INSERT INTO table (fieldValue) VALUES (@newValue)
SELECT @id = SCOPE_IDENTITY()
END
SELECT @id
COMMIT TRANSACTION
you can also use Double-checked locking to reduce locking overhead
DECLARE @id AS INT
SELECT @id = tableID FROM table (NOLOCK) WHERE fieldValue=@newValue
IF @id IS NULL
BEGIN
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
SELECT @id = tableID FROM table WHERE fieldValue=@newValue
IF @id IS NULL
BEGIN
INSERT INTO table (fieldValue) VALUES (@newValue)
SELECT @id = SCOPE_IDENTITY()
END
COMMIT TRANSACTION
END
SELECT @id
As for why ISOLATION LEVEL SERIALIZABLE is necessary, when you are inside a serializable transaction, the first SELECT that hits the table creates a range lock covering the place where the record should be, so nobody else can insert the same record until this transaction ends.
Without ISOLATION LEVEL SERIALIZABLE, the default isolation level (READ COMMITTED) would not lock the table at read time, so between SELECT and UPDATE, somebody would still be able to insert. Transactions with READ COMMITTED isolation level do not cause SELECT to lock. Transactions with REPEATABLE READS lock the record (if found) but not the gap.
Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id
(it won't trigger row update even though id
is assigned to itself).
If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE
.
Even when considering all answers above you might still run into issues that will terminate your maven offline build with an error. Especially, you may experience a warning as follwos:
[WARNING] The POM for org.apache.maven.plugins:maven-resources-plugin:jar:2.6 is missing, no dependency information available
The warning will be immediately followed by further errors and maven will terminate.
For us the safest way to build offline with a maven offline cache created following the hints above is to use following maven offline parameters:
mvn -o -llr -Dmaven.repo.local=<path_to_your_offline_cache> ...
Especially, option -llr prevents you from having to tune your local cache as proposed in answer #4.
Also take care that that the localRepository parameter in settings.xml is set as follows:
<localRepository>${user.home}/.m2/repository</localRepository>
If you want to be sure that these files are properly refreshed by Chrome for all users, then you need to have must-revalidate
in the Cache-Control
header. This will make Chrome re-check files to see if they need to be re-fetched.
Recommend the following response header:
Cache-Control: must-validate
This tells Chrome to check with the server, and see if there is a newer file. If there is a newer file, it will receive it in the response. If not, it will receive a 304 response, and the assurance that the one in the cache is up to date.
If you do NOT set this header, then in the absence of any other setting that invalidates the file, Chrome will never check with the server to see if there is a newer version.
Here is a blog post that discusses the issue further.
According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date
methods and formatting to accomplish your goal:
function dateToString (date) {
// Use an array to format the month numbers
var months = [
"January",
"February",
"March",
...
];
// Use an object to format the timezone identifiers
var timeZones = {
"360": "EST",
...
};
var month = months[date.getMonth()];
var day = date.getDate();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = date.getMinutes();
var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
var timezone = timeZones[date.getTimezoneOffset()];
// Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
return month + " " + day + ", " + year + " - " + time + " " + timezone;
}
var date = new Date("2011-01-28T19:30:00-05:00");
alert(dateToString(date));
You could even take it one step further and override the Date.toString()
method:
function dateToString () { // No date argument this time
// Use an array to format the month numbers
var months = [
"January",
"February",
"March",
...
];
// Use an object to format the timezone identifiers
var timeZones = {
"360": "EST",
...
};
var month = months[*this*.getMonth()];
var day = *this*.getDate();
var year = *this*.getFullYear();
var hours = *this*.getHours();
var minutes = *this*.getMinutes();
var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
var timezone = timeZones[*this*.getTimezoneOffset()];
// Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
return month + " " + day + ", " + year + " - " + time + " " + timezone;
}
var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;
alert(date.toString());
Java 9+:
private byte[] loadPEM(String resource) throws IOException {
URL url = getClass().getResource(resource);
InputStream in = url.openStream();
String pem = new String(in.readAllBytes(), StandardCharsets.ISO_8859_1);
Pattern parse = Pattern.compile("(?m)(?s)^---*BEGIN.*---*$(.*)^---*END.*---*$.*");
String encoded = parse.matcher(pem).replaceFirst("$1");
return Base64.getMimeDecoder().decode(encoded);
}
@Test
public void test() throws Exception {
KeyFactory kf = KeyFactory.getInstance("RSA");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
PrivateKey key = kf.generatePrivate(new PKCS8EncodedKeySpec(loadPEM("test.key")));
PublicKey pub = kf.generatePublic(new X509EncodedKeySpec(loadPEM("test.pub")));
Certificate crt = cf.generateCertificate(getClass().getResourceAsStream("test.crt"));
}
Java 8:
replace the in.readAllBytes()
call with a call to this:
byte[] readAllBytes(InputStream in) throws IOException {
ByteArrayOutputStream baos= new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int read=0; read != -1; read = in.read(buf)) { baos.write(buf, 0, read); }
return baos.toByteArray();
}
thanks to Daniel for noticing API compatibility issues
The change
event not firing on deselection is the desired behaviour. You should run a selector over the entire radio group rather than just the single radio button. And your radio group should have the same name (with different values)
Consider the following code:
$('input[name="job[video_need]"]').on('change', function () {
var value;
if ($(this).val() == 'none') {
value = 'hide';
} else {
value = 'show';
}
$('#video-script-collapse').collapse(value);
});
I have same use case as yours i.e. to show an input box when a particular radio button is selected. If the event was fired on de-selection as well, I would get 2 events each time.
I solved my problem basically with András answer:
1- Log in to MySQL console with root user:
root@9532f0da1a2a:/# mysql -u root -pPASSWORD
And type the root's password to auth.
2- I created a new user:
mysql> CREATE USER 'user'@'hostname' IDENTIFIED BY 'password';
3- Grant all privileges to the new user:
mysql> GRANT ALL PRIVILEGES ON *.* To 'user'@'hostname';
4- Change the Authentication Plugin with the password:
mysql> ALTER USER user IDENTIFIED WITH mysql_native_password BY 'PASSWORD';
Now, phpmyadmin works fine logging the new user.
Thanks for this super helpful post. In case anyone out there (like me!) wants to just have a completely empty cell background in lieu of customizing it through images/text/other content in IB and cannot figure out how the hell to get rid of the dumb border/padding/background even though you set it to clear in IB... here's the code I used that did the trick!
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {
static NSString *cellId = @"cellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellId];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"EditTableViewCell" owner:self options:nil];
cell = cellIBOutlet;
self.cellIBOutlet = nil;
}
cell.backgroundView = [[[UIView alloc] initWithFrame: CGRectZero] autorelease];
[cell.backgroundView setNeedsDisplay];
... any other cell customizations ...
return cell;
}
Hopefully that'll help someone else! Seems to work like a charm.
To determine the brightness of a color with R, I convert the RGB system color in HSV system color.
In my script, I use the HEX system code before for other reason, but you can start also with RGB system code with rgb2hsv {grDevices}
. The documentation is here.
Here is this part of my code:
sample <- c("#010101", "#303030", "#A6A4A4", "#020202", "#010100")
hsvc <-rgb2hsv(col2rgb(sample)) # convert HEX to HSV
value <- as.data.frame(hsvc) # create data.frame
value <- value[3,] # extract the information of brightness
order(value) # ordrer the color by brightness
When using a wildcard, it had to be present on both sides of the refspec, so +refs/heads/*:refs/heads/master
will not work. But you can use +HEAD:refs/heads/master
:
git config remote.heroku.push +HEAD:refs/heads/master
Also, you can do this directly with git push:
git push heroku +HEAD:master
git push -f heroku HEAD:master
use of list comprehension, pd.DataFrame
and pd.concat
pd.concat(
[
df,
pd.DataFrame(
[[np.nan, 'dogs', 3] for _ in range(df.shape[0])],
df.index, ['column_new_1', 'column_new_2','column_new_3']
)
], axis=1)
upper answer only near solving the Problem. heres your answer:
Integer.decode(Character.toString(char c));
The function itself is valid matlab-code. The problem must be something else.
Try calling the function from within the directory it is located or add that directory to your searchpath using addpath('pathname')
.
That’s probably everyone’s first thought. But it’s a little bit more difficult. See Chris Shiflett’s article SERVER_NAME
Versus HTTP_HOST
.
It seems that there is no silver bullet. Only when you force Apache to use the canonical name you will always get the right server name with SERVER_NAME
.
So you either go with that or you check the host name against a white list:
$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
exit;
}
I installed System.Configuration.ConfigurationManager
from Nuget into my .net core 2.2 application.
I then reference using System.Configuration;
Next, I changed
WebConfigurationManager.AppSettings
to ..
ConfigurationManager.AppSettings
So far I believe this is correct. 4.5.0 is typical with .net core 2.2
I have not had any issues with this.
You can also change the index name in column definitions within a create_table
block (such as you get from the migration generator).
create_table :studies do |t|
t.references :user, index: {:name => "index_my_shorter_name"}
end