Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
I was not able to install cv2 on Anaconda-Jupyter notebook running on Ubuntu on Google Cloud Platform. But I found a way to do it as follows:
Run the following command from the ssh terminal and follow the instruction:
sudo apt-get install libsm6 libxrender1 libfontconfig1
Once its installed Open the Jupyter notebook and run following command:
!pip install opencv-contrib-python
Note: I tried to run this command: "sudo python3 -m pip install opencv-contrib-python"but it was showing an error. But above command worked for me.
Now refresh the notebook page and check whether it's installed or not by running import cv2
in the notebook.
I think I found the answer:
In the .service
file, I needed to add /bin/bash
before the path to the script.
For example, for backup.service:
ExecStart=/bin/bash /home/user/.scripts/backup.sh
As opposed to:
ExecStart=/home/user/.scripts/backup.sh
I'm not sure why. Perhaps fish
. On the other hand, I have another script running for my email, and the service file seems to run fine without /bin/bash
. It does use default.target
instead multi-user.target
, though.
Most of the tutorials I came across don't prepend /bin/bash
, but I then saw this SO answer which had it, and figured it was worth a try.
The service file executes the script, and the timer is listed in systemctl --user list-timers
, so hopefully this will work.
Update: I can confirm that everything is working now.
I'll add another case where I was getting the same error but just being a dummy. I had added [routerLinkActiveOptions]="{exact: true}"
without yet adding routerLinkActive="active"
.
My incorrect code was
<a class="nav-link active" routerLink="/dashboard" [routerLinkActiveOptions]="{exact: true}">
Home
</a>
when it should have been
<a class="nav-link active" routerLink="/dashboard" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
Home
</a>
Without having routerLinkActive
, you can't have routerLinkActiveOptions
.
Instead of using Ajax Post method, you can use dynamic form along with element. It will works even page is loaded in SSL and submitted source is non SSL.
You need to set value value of element of form.
Actually new dynamic form will open as non SSL mode in separate tab of Browser when target attribute has set '_blank'
var f = document.createElement('form');
f.action='http://XX.XXX.XX.XX/vicidial/non_agent_api.php';
f.method='POST';
//f.target='_blank';
//f.enctype="multipart/form-data"
var k=document.createElement('input');
k.type='hidden';k.name='CustomerID';
k.value='7299';
f.appendChild(k);
//var z=document.getElementById("FileNameId")
//z.setAttribute("name", "IDProof");
//z.setAttribute("id", "IDProof");
//f.appendChild(z);
document.body.appendChild(f);
f.submit()
I received this error when connecting via SQL Server Management Studio using Windows Authentication. My password had expired but I had not yet changed it. Once changed, I then had to log out and log back in so that the machine was working using my new credentials.
If you are using Dev C++ then your .exe
or mean to say your program already running and you are trying to run it again.
After two dozens of comments to understand the situation, it was found that the libhdf5.so.7
was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.
For future reference: other than checking LD_LIBRARY_PATH
, it's always a good idea to check a library with nm -D
to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum
revealed that the files were actually different.
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
this is how I do it
JAVASCRIPT:
var module = angular.module('yourModuleName', ['ui.router']);
module.run( ['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]);
HTML:
<pre id="uiRouterInfo">
$state = {{$state.current.name}}
$stateParams = {{$stateParams}}
$state full url = {{ $state.$current.url.source }}
</pre>
EXAMPLE
I tried user18490 solution but there were some problems like:
Well after I edited and researched, I was able to come up with a solution. Hopefully it'll work for everyone
Just change the script tag to:
var html = document.documentElement
var body = document.body
var documentHeight = Math.max(body.scrollHeight, body.offsetHeight, html.scrollHeight, html.clientHeight, html.offsetHeight)
var PageHeight = Math.max(html.clientHeight || 0, window.innerHeight || 0)
function scrollDownTo(to, duration) {
if (document.body.scrollTop == to) return;
if ((documentHeight-to) < PageHeight) {
to = documentHeight - PageHeight;
}
var diff = to - window.pageYOffset;
var scrollStep = Math.PI / (duration / 10);
var count = 0, currPos; ajaxe = 1
var start = window.pageYOffset;
var scrollInterval = setInterval(function(){
if (window.pageYOffset != to) {
count = count + 1;
if (ajaxe > count) {
clearInterval(scrollInterval)
}
currPos = start + diff * (0.5 - 0.5 * Math.cos(count * scrollStep));
scroll( 0, currPos)
ajaxe = count
}
else { clearInterval(scrollInterval);}
},20);
}
function test (elID) {
var dest = document.getElementById(elID);
scrollDownTo((dest.getBoundingClientRect().top + window.pageYOffset), 500);
}
The HTML is still the same:
<div class="header">
<p class="menu"><a href="#S1" onclick="test('S1'); return false;">S1</a></p>
<p class="menu"><a href="#S2" onclick="test('S2'); return false;">S2</a></p>
<p class="menu"><a href="#S3" onclick="test('S3'); return false;">S3</a></p>
<p class="menu"><a href="#S4" onclick="test('S4'); return false;">S3</a></p>
</div>
<div style="width: 100%;">
<div id="S1" class="curtain">
blabla
</div>
<div id="S2" class="curtain">
blabla
</div>
<div id="S3" class="curtain">
blabla
</div>
<div id="S4" class="curtain">
blabla
</div>
</div>
If you still encounter any issues kindly comment
For those who need the input file to open directly the camera, you just have to declare capture
parameter to the input file, like this :
<input type="file" accept="image/*" capture>
This is actually pretty easy to fix and doesn't take any coding:
1.Click on the Plots tab above the console. 2.Then at the top right corner of the plots screen click on the options button. 3.Lastly uncheck the "Mute inline plotting" button
Now re-run your script and your graphs should show up in the console.
Cheers.
Problem solved.
Just drop down status bar, touch Choose input method, then change to another input method, type the password again. And everything is OK.
So weird...
Solution from a Chinese BBS. Thanks for the answer's author and all above who try to provide a solution, thanks!
I believe that join()
is just a convenience method. Try df1.merge(df2)
instead, which allows you to specify left_on
and right_on
:
In [30]: left.merge(right, left_on="key1", right_on="key2")
Out[30]:
key1 lval key2 rval
0 foo 1 foo 4
1 bar 2 bar 5
I think this simple method can achieve this goal. With CSS you can turn off pointer event to 'none' then use jQuery to switch classes.
.item{_x000D_
pointer-events:none;_x000D_
}_x000D_
_x000D_
.item.clicked{_x000D_
pointer-events:inherit;_x000D_
}_x000D_
_x000D_
.item:hover,.item:active{_x000D_
/* Your Style On Hover Converted to Tap*/_x000D_
background:#000;_x000D_
}
_x000D_
Use jQuery to switch classed:
jQuery('.item').click(function(e){_x000D_
e.preventDefault();_x000D_
$(this).addClass('clicked')l_x000D_
});
_x000D_
There's a builtin method find on string objects.
s = "Happy Birthday"
s2 = "py"
print(s.find(s2))
Python is a "batteries included language" there's code written to do most of what you want already (whatever you want).. unless this is homework :)
find
returns -1 if the string cannot be found.
I had the same problem - for me it was the SQL Server running out of memory. Freeing up some memory solved the issue
The currently most up-voted and accepted answer and most answers here miss the point.
It doesn't matter how long your function is, or how you name your variable descriptively (to hopefully minimize the chance of potential name collision).
The fact that your function's local variable or its parameter happens to share a name in the global scope is completely irrelevant. And in fact, no matter how carefully you choose you local variable name, your function can never foresee "whether my cool name yadda
will also be used as a global variable in future?". The solution? Simply don't worry about that! The correct mindset is to design your function to consume input from and only from its parameters in signature. That way you don't need to care what is (or will be) in global scope, and then shadowing becomes not an issue at all.
In other words, the shadowing problem only matters when your function need to use the same name local variable and the global variable. But you should avoid such design in the first place. The OP's code does not really have such design problem. It is just that PyCharm is not smart enough and it gives out a warning just in case. So, just to make PyCharm happy, and also make our code clean, see this solution quoting from silyevsk's answer to remove the global variable completely.
def print_data(data):
print data
def main():
data = [4, 5, 6]
print_data(data)
main()
This is the proper way to "solve" this problem, by fixing/removing your global thing, not adjusting your current local function.
The modal dialog can be positioned on top by overriding its z-index property:
.modal.fade {
z-index: 10000000 !important;
}
Now, copy the following content in a script file (like: /backup/mysql-backup.sh) and save on your Linux system.
#!/bin/bash
export PATH=/bin:/usr/bin:/usr/local/bin
TODAY=`date +"%d%b%Y"`
DB_BACKUP_PATH='/backup/dbbackup'
MYSQL_HOST='localhost'
MYSQL_PORT='3306'
MYSQL_USER='root'
MYSQL_PASSWORD='mysecret'
DATABASE_NAME='mydb'
BACKUP_RETAIN_DAYS=30
mkdir -p ${DB_BACKUP_PATH}/${TODAY}
echo "Backup started for database - ${DATABASE_NAME}"
mysqldump -h ${MYSQL_HOST} \
-P ${MYSQL_PORT} \
-u ${MYSQL_USER} \
-p${MYSQL_PASSWORD} \
${DATABASE_NAME} | gzip > ${DB_BACKUP_PATH}/${TODAY}/${DATABASE_NAME}-${TODAY}.sql.gz
if [ $? -eq 0 ]; then
echo "Database backup successfully completed"
else
echo "Error found during backup"
exit 1
fi
##### Remove backups older than {BACKUP_RETAIN_DAYS} days #####
DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`
if [ ! -z ${DB_BACKUP_PATH} ]; then
cd ${DB_BACKUP_PATH}
if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
rm -rf ${DBDELDATE}
fi
fi
After creating or downloading script make sure to set execute permission to run properly.
$ chmod +x /backup/mysql-backup.sh
Edit crontab on your system with crontab -e command. Add following settings to enable backup at 3 in the morning.
0 3 * * * root /backup/mysql-backup.sh
Since you want to append elements to existing list, you can use var List[Int] and then keep on adding elements to the same list. Note -> You have to make sure that you insert an element into existing list as follows:-
var l: List[int] = List() // creates an empty list
l = 3 :: l // adds 3 to the head of the list
l = 4 :: l // makes int 4 as the head of the list
// Now when you will print l, you will see two elements in the list ( 4, 3)
Bootstrap 3
Try this. Simple solution with no dependencies.
$('[data-toggle="collapse"]').click(function() {
$('.collapse.in').collapse('hide')
});
_x000D_
I would do the following to check for an empty object
obj.similar(new JSONObject())
You can use https://github.com/hughsk/flat
Take a nested Javascript object and flatten it, or unflatten an object with delimited keys.
var flatten = require('flat')
flatten({
key1: {
keyA: 'valueI'
},
key2: {
keyB: 'valueII'
},
key3: { a: { b: { c: 2 } } }
})
// {
// 'key1.keyA': 'valueI',
// 'key2.keyB': 'valueII',
// 'key3.a.b.c': 2
// }
var unflatten = require('flat').unflatten
unflatten({
'three.levels.deep': 42,
'three.levels': {
nested: true
}
})
// {
// three: {
// levels: {
// deep: 42,
// nested: true
// }
// }
// }
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
The new git-switch
command (starting in GIT 2.23) also has a flag --discard-changes
which should help you. git pull
might be necessary afterwards.
Warning: it's still considered to be experimental.
My response to a similar question (here) might be useful.
If you have a Model Method defined in the following way:
class MyModel(models.Model):
...
def model_method(self):
return "some_calculated_result"
You can add the result of calling said method to your serializer like so:
class MyModelSerializer(serializers.ModelSerializer):
model_method_field = serializers.CharField(source='model_method')
p.s. Since the custom field isn't really a field in your model, you'll usually want to make it read-only, like so:
class Meta:
model = MyModel
read_only_fields = (
'model_method_field',
)
Slight modification to what was stated above. My Json format, which validates was
{
mycollection:{[
{
property0:value,
property1:value,
},
{
property0:value,
property1:value,
}
]
}
}
Using AlexDev's response, I did this Looping each child, creating reader from it
public partial class myModel
{
public static List<myModel> FromJson(string json) => JsonConvert.DeserializeObject<myModelList>(json, Converter.Settings).model;
}
public class myModelList {
[JsonConverter(typeof(myModelConverter))]
public List<myModel> model { get; set; }
}
class myModelConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var list = Activator.CreateInstance(objectType) as System.Collections.IList;
var itemType = objectType.GenericTypeArguments[0];
foreach (var child in token.Children()) //mod here
{
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(child.CreateReader(), newObject); //mod here
list.Add(newObject);
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
Try to surround the path with quotes, and remove the spaces
export PYTHONPATH="/home/user/my_project":$PYTHONPATH
And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)
Execute the following command to check everything is configured correctly:
echo $PYTHONPATH
If you look at the chain of exceptions, the problem is
Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property salt in class backend.Account
The problem is that the method Account.setSalt() works fine when you create an instance but not when you retrieve an instance from the database. This is because you don't want to create a new salt each time you load an Account.
To fix this, create a method setSalt(long) with visibility private and Hibernate will be able to set the value (just a note, I think it works with Private, but you might need to make it package or protected).
If you have untarred your own version of tomcat v8 with a root user into a custom directory (linux) then the default permissions on the TOMCATROOT/lib directory do not allow normal user access.
Eclipse will not be able to see the catalina.jar to check the version. So no amount of fiddling aorund with the server.properties will help!
just add chmod u+x lib/ to allow normal user access to the libs.
As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost';
does not work is quite simple : There is no grant called USAGE
.
The actual named grants are in the MySQL Documentation
The grant USAGE
is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user
where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE
. Running DROP USER 'phpmyadmin'@'localhost';
should work just fine. Under the hood, it's really doing this:
DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;
Therefore, the removal of a row from mysql.user
constitutes running REVOKE USAGE
, even though REVOKE USAGE
cannot literally be executed.
Okay so ideal permissions look like this
For ssh directory (You can get this by typing ls -ld ~/.ssh/
)
drwx------ 2 oroborus oroborus 4096 Nov 28 12:05 /home/oroborus/.ssh/
d means directory, rwx means the user oroborus has read write and execute permission. Here oroborus is my computer name, you can find yours by echoing $USER. The second oroborus is actually the group. You can read more about what does each field mean here. It is very important to learn this because if you are working on ubuntu/osx or any Linux distro chances are you will encounter it again.
Now to make your permission look like this, you need to type
sudo chmod 700 ~/.ssh
7 in binary is 111 which means read 1 write 1 and execute 1, you can decode 6 by similar logic means only read-write permissions
You have given your user read write and execute permissions. Make sure your file permissions look like this.
total 20
-rw------- 1 oroborus oroborus 418 Nov 8 2014 authorized_keys
-rw------- 1 oroborus oroborus 34 Oct 19 14:25 config
-rw------- 1 oroborus oroborus 1679 Nov 15 2015 id_rsa
-rw------- 1 oroborus oroborus 418 Nov 15 2015 id_rsa.pub
-rw-r--r-- 1 oroborus root 222 Nov 28 12:12 known_hosts
You have given here read-write permission to your user here for all files.
You can see this by typing ls -l ~/.ssh/
This issue occurs because ssh is a program is trying to write to a file called known_hosts in its folder. While writing if it knows that it doesn't have sufficient permissions it will not write in that file and hence fail. This is my understanding of the issue, more knowledgeable people can throw more light in this. Hope it helps
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
I had this same problem and stumbled upon the following simple solution. Just add a bit of padding to the image and it resizes itself to fit within the div.
<div class="col-sm-3">
<img src="xxx.png" class="img-responsive" style="padding-top: 5px">
</div>
The resolution is to use TypedQuery instead. When creating a query from the EntityManager instead call it like this:
TypedQuery<[YourClass]> query = entityManager.createQuery("[your sql]", [YourClass].class);
List<[YourClass]> list = query.getResultList(); //no type warning
This also works the same for named queries, native named queries, etc. The corresponding methods have the same names as the ones that would return the vanilla query. Just use this instead of a Query whenever you know the return type.
It's funny because I'm learning Angular myself and was watching some video's from their channel on Youtube. The speaker mentions your exact problem in this video https://www.youtube.com/watch?v=ZhfUv0spHCY#t=1681 around the 28:30 minute mark.
It comes down to placing that particular piece of code in a service rather then a controller.
My guess would be to inject new popup elements into the DOM and handle them separate instead of showing and hiding the same element. This way you can have multiple popups.
The whole video is very interesting to watch as well :-)
Maybe the following is what you are looking for:
SELECT name, pathfilename
FROM table1
NATURAL JOIN table2
NATURAL JOIN table3
WHERE name = 'John';
Have you looked at the samples provided with EPPlus?
This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample
This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample
This is how we use the package to generate a file.
var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
// do work here
xlPackage.Save();
}
It's best if you judge on your own,
1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).
http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text
This Link is no more working so please watch this video for similar details Video
Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)
Some Variation: Some user find plugins useful for PHP coders on that
http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html
although, there are many plugins for Notepad Plus Plus ..
I am not sure of your requirements, nor I am promoter of either of these editors :)
So, judge on basis of your requirements, this should satisfy you query...
Yes we can add that both are evolving and changing fast..
Have a look at the example in this link :
http://docs.angularjs.org/api/ngSanitize.$sanitize
Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :
If you already have done all this :
// My magic HTML string function.
function htmlString (str) {
return "<h1>" + str + "</h1>";
}
function Ctrl ($scope) {
var str = "HELLO!";
$scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];
Then in your html within the scope of that controller, you could
<div ng-bind-html="htmlString"></div>
The below code is tested by myself and is very simple, understandable, usable and fast. This code, initially takes all sheet names, then puts all tables of that excel file in a DataSet.
public static DataSet ToDataSet(string exceladdress, int startRecord = 0, int maxRecord = -1, string condition = "")
{
DataSet result = new DataSet();
using (OleDbConnection connection = new OleDbConnection(
(exceladdress.TrimEnd().ToLower().EndsWith("x"))
? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + exceladdress + "';" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'"
: "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + exceladdress + "';Extended Properties=Excel 8.0;"))
try
{
connection.Open();
DataTable schema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow drSheet in schema.Rows)
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
string s = drSheet["TABLE_NAME"].ToString();
if (s.StartsWith("'")) s = s.Substring(1, s.Length - 2);
System.Data.OleDb.OleDbDataAdapter command =
new System.Data.OleDb.OleDbDataAdapter(string.Join("", "SELECT * FROM [", s, "] ", condition), connection);
DataTable dt = new DataTable();
if (maxRecord > -1 && startRecord > -1) command.Fill(startRecord, maxRecord, dt);
else command.Fill(dt);
result.Tables.Add(dt);
}
return result;
}
catch (Exception ex) { return null; }
finally { connection.Close(); }
}
Enjoy...
My impression is that R CMD BATCH
is a bit of a relict. In any case, the more recent Rscript
executable (available on all platforms), together with commandArgs()
makes processing command line arguments pretty easy.
As an example, here is a little script -- call it "myScript.R"
:
## myScript.R
args <- commandArgs(trailingOnly = TRUE)
rnorm(n=as.numeric(args[1]), mean=as.numeric(args[2]))
And here is what invoking it from the command line looks like
> Rscript myScript.R 5 100
[1] 98.46435 100.04626 99.44937 98.52910 100.78853
Edit:
Not that I'd recommend it, but ... using a combination of source()
and sink()
, you could get Rscript
to produce an .Rout
file like that produced by R CMD BATCH
. One way would be to create a little R script -- call it RscriptEcho.R
-- which you call directly with Rscript. It might look like this:
## RscriptEcho.R
args <- commandArgs(TRUE)
srcFile <- args[1]
outFile <- paste0(make.names(date()), ".Rout")
args <- args[-1]
sink(outFile, split = TRUE)
source(srcFile, echo = TRUE)
To execute your actual script, you would then do:
Rscript RscriptEcho.R myScript.R 5 100
[1] 98.46435 100.04626 99.44937 98.52910 100.78853
which will execute myScript.R
with the supplied arguments and sink interleaved input, output, and messages to a uniquely named .Rout
.
Edit2:
You can run Rscript verbosely and place the verbose output in a file.
Rscript --verbose myScript.R 5 100 > myScript.Rout
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet
of Note
s, where you need to pass in a single Note
.
You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
This is are other ways of printing empty lines in python
# using \n after the string creates an empty line after this string is passed to the the terminal.
print("We need to put about", average_passengers_per_car, "in each car. \n")
print("\n") #prints 2 empty lines
print() #prints 1 empty line
Consider the easy, lightweight Java library EasyFlow. From their docs:
With EasyFlow you can:
- implement complex logic but keep your code simple and clean
- handle asynchronous calls with ease and elegance
- avoid concurrency by using event-driven programming approach
- avoid StackOverflow error by avoiding recursion
- simplify design, programming and testing of complex java applications
By "camera position," it sounds like you want to adjust the elevation and the azimuth angle that you use to view the 3D plot. You can set this with ax.view_init
. I've used the below script to first create the plot, then I determined a good elevation, or elev
, from which to view my plot. I then adjusted the azimuth angle, or azim
, to vary the full 360deg around my plot, saving the figure at each instance (and noting which azimuth angle as I saved the plot). For a more complicated camera pan, you can adjust both the elevation and angle to achieve the desired effect.
from mpl_toolkits.mplot3d import Axes3D
ax = Axes3D(fig)
ax.scatter(xx,yy,zz, marker='o', s=20, c="goldenrod", alpha=0.6)
for ii in xrange(0,360,1):
ax.view_init(elev=10., azim=ii)
savefig("movie%d.png" % ii)
Quote (read [here][1])-
When you use CAST to convert a CLOB value into a character datatype or a BLOB value into the RAW datatype, the database implicitly converts the LOB value to character or raw data and then explicitly casts the resulting value into the target datatype.
So, something like this should work-
report := CAST(report_clob AS VARCHAR2(100));
Or better yet use it as CAST(report_clob AS VARCHAR2(100))
where ever you are trying to use the BLOB
as VARCHAR
[1]: http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions016.htm
I wanted to use this in an Angular (6) library today and it took me a while to get this to work as expected.
In order for my library to use declarations I had to use the d.ts
extention for the file that declares the new properties of the global object.
So in the end, the file ended up with something like:
/path-to-angular-workspace/angular-workspace/projects/angular-library/src/globals.d.ts
Once created, don't forget to expose it in your public_api.ts
.
That did it for me. Hope this helps.
Solution using just POST - no $_SESSION
page1.php
<form action="page2.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
page2.php
<?php
// this page outputs the contents of the textarea if posted
$textarea1 = ""; // set var to avoid errors
if(isset($_POST['textarea1'])){
$textarea1 = $_POST['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
Solution using $_SESSION and POST
page1.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
$textarea1 = "";
if(isset($_POST['textarea1'])){
$_SESSION['textarea1'] = $_POST['textarea1'];
}
?>
<form action="page1.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>
page2.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
// this page outputs the textarea1 from the session IF it exists
$textarea1 = ""; // set var to avoid errors
if(isset($_SESSION['textarea1'])){
$textarea1 = $_SESSION['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
WARNING!!! - This contains no validation!!!
I was able to fix my problem by using a combination of $.ajaxSetup and appending a timestamp to the url of my post (not to the post parameters/body). This based on the recommendations of previous answers
$(document).ready(function(){
$.ajaxSetup({ type:'POST', headers: {"cache-control","no-cache"}});
$('#myForm').submit(function() {
var data = $('#myForm').serialize();
var now = new Date();
var n = now.getTime();
$.ajax({
type: 'POST',
url: 'myendpoint.cfc?method=login&time='+n,
data: data,
success: function(results){
if(results.success) {
window.location = 'app.cfm';
} else {
console.log(results);
alert('login failed');
}
}
});
});
});
I'd use a set myself, but here's yet another way:
uniquewords = []
while True:
ipta = raw_input("Word: ")
if ipta == "":
break
if not ipta in uniquewords:
uniquewords.append(ipta)
print "There are", len(uniquewords), "unique words!"
Recently I used an AS3 engine: PushButton (now is dead, but it's still functional and you could use something else) to do this job. To make it works with Android and iOS, the project was compiled in AIR for both platforms and everything worked with no performance damage. Since Flash Builder is kinda expensive ($249), you could use FlashDevelop (there is some tutorials to compile in AIR with it).
Flash could be an option since is very easy to learn.
Unfortunately, all the good answers here didn't work for me. So after installing composer on windows 10, I just had to set system variable
in environment variables
and it worked.
You can use the pathlib module.
from pathlib import Path
x = Path('./')
print(list(filter(lambda y:y.is_file(), x.iterdir())))
Building off of Mamboking's answer:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(anyString())).thenReturn("Some result");
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Addressing your request to verify whether the argument contains a certain value, I could assume you mean that the argument is a String and you want to test whether the String argument contains a substring. For this you could do:
ArgumentCaptor<String> savedCaptor = ArgumentCaptor.forClass(String.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains("substring I want to find");
If that assumption was wrong, and the argument to save()
is a collection of some kind, it would be only slightly different:
ArgumentCaptor<Collection<MyType>> savedCaptor = ArgumentCaptor.forClass(Collection.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains(someMyTypeElementToFindInCollection);
You might also check into ArgumentMatchers, if you know how to use Hamcrest matchers.
Yes, I was late, but I can add for Assemble users: you can use buil-in "parseJSON"
helper http://assemble.io/helpers/helpers-data.html. (Discovered in https://github.com/assemble/assemble/issues/416).
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";_x000D_
var person = {[key]:"John"};_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};_x000D_
var key = "name";_x000D_
_x000D_
person[key] /* this is same as person.name */ = "John";_x000D_
_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
Necromancing:
It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:
;WITH baseTable AS
(
SELECT 'RM1' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr
FROM baseTable
)
SELECT
RM
,ADR
,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1
,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2
-- Not supported
--,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu
FROM CTE
Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:layout_marginTop="8dp"
android:background="@drawable/edit_border"
android:visibility="visible"
android:id="@+id/teach_repeat"
android:entries="@array/on_off"
android:textSize="12sp"
android:textColor="#ffffff"
android:layout_width="match_parent"
android:layout_height="40dp" />
<ImageView
android:layout_marginTop="8dp"
android:layout_gravity="end"
android:src="@drawable/ic_arrow_drop_down_white_18dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
I think our solution was sufficiently different from everyone elses so I'll document it here.
We have setup of Main layout, an intermediary layout and then the final action page render. Main.cshtml <- Config.cshtml <- Action.cshtml
Only when web.config had customErrors='On/RemoteOnly'
we got a custom error and no exception nor Application_Error
was called. I could catch this on Layout = null
line in the Error.cshtml. Exception was as in the question, missing scripts section.
We did have it defined in Main.cshtml (with required:false) and Action.cshtml didn't have anything that wrote into the scripts section.
Solution was to add @section scripts { @RenderSection("scripts", false) }
to Config.cshtml.
There is extensive paramiko API documentation you can find at: http://docs.paramiko.org/en/stable/index.html
I use the following method to execute commands on a password protected client:
import paramiko
nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username'
password = 'password'
command = 'ls'
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
stdout_data = []
stderr_data = []
session = client.open_channel(kind='session')
session.exec_command(command)
while True:
if session.recv_ready():
stdout_data.append(session.recv(nbytes))
if session.recv_stderr_ready():
stderr_data.append(session.recv_stderr(nbytes))
if session.exit_status_ready():
break
print 'exit status: ', session.recv_exit_status()
print ''.join(stdout_data)
print ''.join(stderr_data)
session.close()
client.close()
INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');
the above mentioned code is not correct because your first parameter POSTCODE is of type VARCHAR(10)
. you should have used ' '
.
try INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');
Another option to resolve issue described in OP which I encountered on recent bootcamp training is using window.setTimeout to wrap around the code which is bothersome. My understanding is that it delays the execution of the function for the specified time period (500ms in this case), allowing enough time for the page to load. So, for example:
<script type = "text/javascript">
window.setTimeout(function(){
alert("Hello World!");
}, 500);
</script>
You can insert into a table from a SELECT.
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
(SELECT id FROM state WHERE name = 'New York'),
(SELECT id FROM positions WHERE name = 'Sales Executive'),
(SELECT id FROM manager WHERE name = 'Barry Green')
FROM
dual
Or, similarly...
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
state.id,
positions.id,
manager.id
FROM
state
CROSS JOIN
positions
CROSS JOIN
manager
WHERE
state.name = 'New York'
AND positions.name = 'Sales Executive'
AND manager.name = 'Barry Green'
Though this one does assume that all the look-ups exist. If, for example, there is no position name 'Sales Executive', nothing would get inserted with this version.
This is what i have been facing for long time.
This happened last time and figured out that one case could be a bad war deployment, which came after i update library/maven dependencies on pom and re installed it.
SOLUTION:
right click on the server > remove the war and
right click on the server again > clean
make sure the maven dependencies are added to deployment assembly
right click on the project > Run As > maven clean
right click on the project again > Run As > maven install
and finally deploy the project on to the server. This helped me to solve the issue
Not sure why this wasnt mentioned before, but the only thing that worked for me (on my NVIDIA Xavier) was:
sudo apt-get install python3-pip
(or sudo apt-get install python-pip
for python 2)
I have faced the similar issue and fixed by copying the missing Jar files in to .M2 Path,
For example: if you see the error message as Missing artifact tws:axis-client:jar:8.7
then you have to download "axis-client-8.7.jar" file and paste the same in to below location will resolve the issue.
C:\Users\UsernameXXX.m2\repository\tws\axis-client\8.7(Paste axis-client-8.7.jar).
finally, right click on project->Maven->Update Project...Thats it.
happy coding.
This solution has the benefit of showing the URL of the linked-to page on hover, as most browsers do by default, instead of history.go(-1)
or similar:
<script>
document.write('<a href="' + document.referrer + '">Go Back</a>');
</script>
I did a little more research and I am updating my answer with a more current solution. I am not sure if you have already looked at it but there is a nice sample code provided by Apple.
Download the sample code here
Include the Reachability.h and Reachability.m files in your project. Take a look at ReachabilityAppDelegate.m to see an example on how to determine host reachability, reachability by WiFi, by WWAN etc. For a very simply check of network reachability, you can do something like this
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if (networkStatus == NotReachable) {
NSLog(@"There IS NO internet connection");
} else {
NSLog(@"There IS internet connection");
}
@BenjaminPiette's: Don't forget to add SystemConfiguration.framework to your project.
I've tried both these and still get failure due to conflicts. At the end of my patience, I cloned master in another location, copied everything into the other branch and committed it. which let me continue. The "-X theirs" option should have done this for me, but it did not.
git merge -s recursive -X theirs master
error: 'merge' is not possible because you have unmerged files. hint: Fix them up in the work tree, hint: and then use 'git add/rm ' as hint: appropriate to mark resolution and make a commit, hint: or use 'git commit -a'. fatal: Exiting because of an unresolved conflict.
In sybase_driver.php
/**
* Manejador de Mensajes de Error Sybase
* Autor: Isaí Moreno
* Fecha: 06/Nov/2019
*/
static $CODE_ERROR_SYBASE;
public static function SetCodeErrorSybase($Code) {
if ($Code != 3621) { /*No se toma en cuenta el código de command aborted*/
CI_DB_sybase_driver::$CODE_ERROR_SYBASE = trim(CI_DB_sybase_driver::$CODE_ERROR_SYBASE.' '.$Code);
}
}
public static function GetCodeErrorSybase() {
return CI_DB_sybase_driver::$CODE_ERROR_SYBASE;
}
public static function msg_handler($msgnumber, $severity, $state, $line, $text)
{
log_message('info', 'CI_DB_sybase_driver - CODE ERROR ['.$msgnumber.'] Mensaje - '.$text);
CI_DB_sybase_driver::SetCodeErrorSybase($msgnumber);
}
// ------------------------------------------------------------------------
Add and modify the following methods in the same sybase_driver.php file
/**
* The error message number
*
* @access private
* @return integer
*/
function _error_number()
{
// Are error numbers supported?
return CI_DB_sybase_driver::GetCodeErrorSybase();
}
function _sybase_set_message_handler()
{
// Are error numbers supported?
return sybase_set_message_handler('CI_DB_sybase_driver::msg_handler');
}
Implement in the function of a controller.
public function Eliminar_DUPLA(){
if($this->session->userdata($this->config->item('mycfg_session_object_name'))){
//***/
$Operacion_Borrado_Exitosa=false;
$this->db->trans_begin();
$this->db->_sybase_set_message_handler(); <<<<<------- Activar Manejador de errores de sybase
$Dupla_Eliminada=$this->Mi_Modelo->QUERY_Eliminar_Dupla($PARAMETROS);
if ($Dupla_Eliminada){
$this->db->trans_commit();
MostrarNotificacion("Se eliminó DUPLA exitosamente","OK",true);
$Operacion_Borrado_Exitosa=true;
}else{
$Error = $this->db->_error_number(); <<<<----- Obtengo el código de error de sybase para personilzar mensaje al usuario
$this->db->trans_rollback();
MostrarNotificacion("Ocurrio un error al intentar eliminar Dupla","Error",true);
if ($Error == 547) {
MostrarNotificacion("<strong>Código de error :[".$Error.']. No se puede eliminar documento Padre.</strong>',"Error",true);
} else {
MostrarNotificacion("<strong>Código de Error :[".$Error.']</strong><br>',"Error",true);
}
}
echo "@".Obtener_Contador_Notificaciones();
if ($Operacion_Borrado_Exitosa){
echo "@T";
}else{
echo "@F";
}
}else{
redirect($this->router->default_controller);
}
}
In the log you can check the codes and messages sent by the database server.
INFO - 2019-11-06 19:26:33 -> CI_DB_sybase_driver - CODE ERROR [547] Message - Dependent foreign key constraint violation in a referential integrity constraint. dbname = 'database', table name = 'mitabla', constraint name = 'FK_SR_RELAC_REFERENCE_SR_mitabla'. INFO - 2019-11-06 19:26:33 -> CI_DB_sybase_driver - CODE ERROR [3621] Message - Command has been aborted. ERROR - 2019-11-06 19:26:33 -> Query error: - Invalid query: delete from mitabla where ID = 1019.
It happens due to a missing plugin configuration (as per vaadin's demo pom.xml comment):
This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e ettings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>com.vaadin</groupId>
<artifactId>
vaadin-maven-plugin
</artifactId>
<versionRange>
[7.1.5,)
</versionRange>
<goals>
<goal>resources</goal>
<goal>update-widgetset</goal>
<goal>compile</goal>
<goal>update-theme</goal>
<goal>compile-theme</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
First, I don't understand why you are adding all the keys and values count times, Index is never used.
I tried this example :
var source = new BindingSource();
List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"), new MyStruct("c","d") };
source.DataSource = list;
grid.DataSource = source;
and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.
class MyStruct
{
public string Name { get; set; }
public string Adres { get; set; }
public MyStruct(string name, string adress)
{
Name = name;
Adres = adress;
}
}
Try to build a type that takes one key and value, and add it one by one. Hope this helps.
You will need to store the image in the database as a BLOB.
you will want to create a column called PHOTO in your table and set it as a mediumblob.
Then you will want to get it from the form like so:
$data = file_get_contents($_FILES['photo']['tmp_name']);
and then set the column to the value in $data.
Of course, this is bad practice and you would probably want to store the file on the system with a name that corresponds to the users account.
You can make a link perform an Ajax post request when it's clicked.
In jQuery:
$('a').click(function(e) {
var $this = $(this);
e.preventDefault();
$.post('url', {'user': 'something', 'foo': 'bar'}, function() {
window.location = $this.attr('href');
});
});
You could also make the link submit a POST form with JavaScript:
<form action="url" method="post">
<input type="hidden" name="user" value="something" />
<a href="#">CLick</a>
</form>
<script>
$('a').click(function(e) {
e.preventDefault();
$(this).parents('form').submit();
});
</script>
With Java 8, you can easily achieve time in String format from long seconds like,
LocalTime.ofSecondOfDay(86399L)
Here, given value is max allowed to convert (upto 24 hours) and result will be
23:59:59
Pros : 1) No need to convert manually and to append 0 for single digit
Cons : work only for up to 24 hours
const string message = "Hello" + ",world" + exclam;
The +
operator has left-to-right associativity, so the equivalent parenthesized expression is:
const string message = (("Hello" + ",world") + exclam);
As you can see, the two string literals "Hello"
and ",world"
are "added" first, hence the error.
One of the first two strings being concatenated must be a std::string
object:
const string message = string("Hello") + ",world" + exclam;
Alternatively, you can force the second +
to be evaluated first by parenthesizing that part of the expression:
const string message = "Hello" + (",world" + exclam);
It makes sense that your first example (hello + ",world" + "!"
) works because the std::string
(hello
) is one of the arguments to the leftmost +
. That +
is evaluated, the result is a std::string
object with the concatenated string, and that resulting std::string
is then concatenated with the "!"
.
As for why you can't concatenate two string literals using +
, it is because a string literal is just an array of characters (a const char [N]
where N
is the length of the string plus one, for the null terminator). When you use an array in most contexts, it is converted into a pointer to its initial element.
So, when you try to do "Hello" + ",world"
, what you're really trying to do is add two const char*
s together, which isn't possible (what would it mean to add two pointers together?) and if it was it wouldn't do what you wanted it to do.
Note that you can concatenate string literals by placing them next to each other; for example, the following two are equivalent:
"Hello" ",world"
"Hello,world"
This is useful if you have a long string literal that you want to break up onto multiple lines. They have to be string literals, though: this won't work with const char*
pointers or const char[N]
arrays.
Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:
private DataTable LoadExcelData(string fileName)
{
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);
myCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
return dt;
}
You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.
With the IDLE editor you can use this:
Set it the same way you'd set the width of any other HTML element, with CSS:
audio { width: 200px; }
Note that audio
is an inline element by default in Firefox, so you might also want to set it to display: block
. Here's an example.
There's a really good paper by Microsoft Research called To Blob or Not To Blob.
Their conclusion after a large number of performance tests and analysis is this:
if your pictures or document are typically below 256KB in size, storing them in a database VARBINARY column is more efficient
if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)
in between those two, it's a bit of a toss-up depending on your use
If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.
For filegroups, check out Files and Filegroup Architecture for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".
Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:
CREATE TABLE dbo.YourTable
(....... define the fields here ......)
ON Data -- the basic "Data" filegroup for the regular data
TEXTIMAGE_ON LARGE_DATA -- the filegroup for large chunks of data
Check out the MSDN intro on filegroups, and play around with it!
class Program
{
static void Main(string[] args)
{
//Load XML from local
string sourceFileName="";
string element=string.Empty;
var FolderPath=@"D:\Test\RenameFileWithXmlAttribute";
string[] files = Directory.GetFiles(FolderPath, "*.xml");
foreach (string xmlfile in files)
{
try
{
sourceFileName = xmlfile;
XElement xele = XElement.Load(sourceFileName);
string convertToString = xele.ToString();
XElement parseXML = XElement.Parse(convertToString);
element = parseXML.Descendants("Meta").Where(x => (string)x.Attribute("name") == "XMLTAG").Last().Value;
DirectoryInfo CurrentDate = Directory.CreateDirectory(DateTime.Now.ToString("yyyy-MM-dd"));
string saveWithThisName= Path.Combine(CurrentDate.FullName, element);
File.Copy(sourceFileName, saveWithThisName,true);
}
catch(Exception ex)
{
}
}
}
}
If your project budged allows you to have enough RAM memory on your environment - answer is Redis. Especially taking in account new Redis 3.2 with cluster functionality.
On Jupyter Notebooks on Anaconda, doing this:
%load_ext autoreload
%autoreload 2
produced the message:
The autoreload extension is already loaded. To reload it, use:
%reload_ext autoreload
It looks like it's preferable to do:
%reload_ext autoreload
%autoreload 2
Version information:
The version of the notebook server is 5.0.0 and is running on: Python 3.6.2 |Anaconda, Inc.| (default, Sep 20 2017, 13:35:58) [MSC v.1900 32 bit (Intel)]
try
{
// load the assembly or type
}
catch (Exception ex)
{
if (ex is System.Reflection.ReflectionTypeLoadException)
{
var typeLoadException = ex as ReflectionTypeLoadException;
var loaderExceptions = typeLoadException.LoaderExceptions;
}
}
Most of you already know this by now, but I am posting this, just incase, some of you are still struggling with JSON in iOS6+.
In iOS6 and later, we have the NSJSONSerialization Class that is fast and has no dependency on including "outside" libraries.
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
This is the way iOS6 and later can now parse JSON efficiently.The use of SBJson is also pre-ARC implementation and brings with it those issues too if you are working in an ARC environment.
I hope this helps!
Not sure if the cleanest for long commands but certainly the easiest:
ssh user@host "cmd1; cmd2; cmd3"
I tried almost all of this. but still couldn't work. Finally I found it was because of 24bitmap problems. If you tried some bitmap which less than 24bit. Most of those above methods should work.
Best solution would be to use writing-mode
writing-mode: vertical-rl;
https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode
It defines whether lines of text are laid out horizontally or vertically and the direction in which blocks progress.
It has good browser support, but will not work on IE8 (if you care about IE) http://caniuse.com/#feat=css-writing-mode
Here's a little cmd script you can copy-n-paste into a file named something like where.cmd
:
@echo off
rem - search for the given file in the directories specified by the path, and display the first match
rem
rem The main ideas for this script were taken from Raymond Chen's blog:
rem
rem http://blogs.msdn.com/b/oldnewthing/archive/2005/01/20/357225.asp
rem
rem
rem - it'll be nice to at some point extend this so it won't stop on the first match. That'll
rem help diagnose situations with a conflict of some sort.
rem
setlocal
rem - search the current directory as well as those in the path
set PATHLIST=.;%PATH%
set EXTLIST=%PATHEXT%
if not "%EXTLIST%" == "" goto :extlist_ok
set EXTLIST=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
:extlist_ok
rem - first look for the file as given (not adding extensions)
for %%i in (%1) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i
rem - now look for the file adding extensions from the EXTLIST
for %%e in (%EXTLIST%) do @for %%i in (%1%%e) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i
Google Chrome now supports this (Developer Tools > Network > [XHR item in list] Preview
).
In addition, you can use a third party tool to format the json content. Here's one that presents a tree view, and here's another that merely formats the text (and does validation).
Consider adding this to your CSS to resolve the problem:
button {
margin: 0 auto;
display: block;
}
The Distinct()
is going to mess up the ordering, so you'll have to the sorting after that.
var uniqueColors =
(from dbo in database.MainTable
where dbo.Property == true
select dbo.Color.Name).Distinct().OrderBy(name=>name);
<a href="#"><button>Link Text</button></a>
You asked for a link that looks like a button, so use a link and a button :-) This will preserve default browser button styling. The button by itself does nothing, but clicking it activates its parent link.
Demo:
<a href="http://stackoverflow.com"><button>Link Text</button></a>
_x000D_
To add some more advice combining the suggestions of @kingjeffrey and @CMS: You can use loop
where it is available and fall back on kingjeffrey's event handler when it isn't. There's a good reason why you want to use loop
and not write your own event handler: As discussed in the Mozilla bug report, while loop
currently doesn't loop seamlessly (without a gap) in any browser I know of, it's certainly possible and likely to become standard in the future. Your own event handler will never be seamless in any browser (since it has to pump around through the JavaScript event loop). Therefore, it's best to use loop
where possible instead of writing your own event. As CMS pointed out in a comment on Anurag's answer, you can detect support for loop
by querying the loop
variable -- if it is supported it will be a boolean (false), otherwise it will be undefined, as it currently is in Firefox.
Putting these together:
myAudio = new Audio('someSound.ogg');
if (typeof myAudio.loop == 'boolean')
{
myAudio.loop = true;
}
else
{
myAudio.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
}
myAudio.play();
I was facing the same problem called "Content is not allowed in prolog" in my xml file.
Solution
Initially my root folder was '#Filename'.
When i removed the first character '#' ,the error got resolved.
No need of removing the #filename... Try in this way..
Instead of passing a File or URL object to the unmarshaller method, use a FileInputStream.
File myFile = new File("........");
Object obj = unmarshaller.unmarshal(new FileInputStream(myFile));
UPDATE
the super finishAffinity()
method will help to reduce the code but achieve the same. It will finish the current activity as well as all activities in the stack, use getActivity().finishAffinity()
if you are in a fragment.
finishAffinity();
startActivity(new Intent(mActivity, LoginActivity.class));
ORIGINAL ANSWER
Assume that LoginActivity --> HomeActivity --> ... --> SettingsActivity call signOut():
void signOut() {
Intent intent = new Intent(this, HomeActivity.class);
intent.putExtra("finish", true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // To clean up all activities
startActivity(intent);
finish();
}
HomeActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean finish = getIntent().getBooleanExtra("finish", false);
if (finish) {
startActivity(new Intent(mContext, LoginActivity.class));
finish();
return;
}
initializeView();
}
This works for me, hope that it is helpful for you too. :)
It depends how many rows are returned in $results
, and how many columns there are in $row
?
At the moment I'm writing this, the trick with m.facebook.com no longer works (at least for me) and user is redirected to the mobile FB login page which obviously is not good for UX.
Fortunately, FB PHP SDK has a semi-documented solution (in case the link doesn't lead to getLogoutUrl()
function, just search look for it on that page). This is also mentioned in at least one other on StackOverflow: Facebook php SDK getLogoutUrl() problem.
BTW I've just noticed that Zach Greenberg got it right in this question, but I'm adding my answer as a summary for Python developers.
readelf -a xxx
INTERP
0x0000000000000238 0x0000000000400238 0x0000000000400238
0x000000000000001c 0x000000000000001c R 1
[Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)
#include <sys/types.h>
In order to execute multiple programs, I also needed a profiles
section:
<profiles>
<profile>
<id>traverse</id>
<activation>
<property>
<name>traverse</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<argument>org.dhappy.test.NeoTraverse</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
This is then executable as:
mvn exec:exec -Ptraverse
I wrote a nifty script for this called Gitter using the REST APIs for GitHub and BitBucket:
https://github.com/dderiso/gitter
BitBucket:
gitter -c -r b -l javascript -n node_app
GitHub:
gitter -c -r g -l javascript -n node_app
-c
= create new repo-r
= repo provider (g = GitHub, b = BitBucket)-n
= name the repo-l
= (optional) set the language of the app in the repoOkay I fixed this thing. Had to first convert the projects to Maven Projects, then remove them from the Eclipse workspace, and then re-import them.
private List<string> strs = new List<string>();
char[] numbersArray;
private int End = 0;
private int numberOfStrings;
private void PrintLetters(string numbers)
{
this.End = numbers.Length;
this.numbersArray = numbers.ToCharArray();
this.PrintAllCombinations(this.GetCharacters(this.numbersArray[0]), string.Empty, 0);
}
private void PrintAllCombinations(char[] letters, string output, int depth)
{
depth++;
for (int i = 0; i < letters.Length; i++)
{
if (depth != this.End)
{
output += letters[i];
this.PrintAllCombinations(this.GetCharacters(Convert.ToChar(this.numbersArray[depth])), output, depth);
output = output.Substring(0, output.Length - 1);
}
else
{
Console.WriteLine(output + letters[i] + (++numberOfStrings));
}
}
}
private char[] GetCharacters(char x)
{
char[] arr;
switch (x)
{
case '0': arr = new char[1] { '.' };
return arr;
case '1': arr = new char[1] { '.' };
return arr;
case '2': arr = new char[3] { 'a', 'b', 'c' };
return arr;
case '3': arr = new char[3] { 'd', 'e', 'f' };
return arr;
case '4': arr = new char[3] { 'g', 'h', 'i' };
return arr;
case '5': arr = new char[3] { 'j', 'k', 'l' };
return arr;
case '6': arr = new char[3] { 'm', 'n', 'o' };
return arr;
case '7': arr = new char[4] { 'p', 'q', 'r', 's' };
return arr;
case '8': arr = new char[3] { 't', 'u', 'v' };
return arr;
case '9': arr = new char[4] { 'w', 'x', 'y', 'z' };
return arr;
default: return null;
}
}
Here is way I tried and found useful,
URL u = new URL(name); // this would check for the protocol
u.toURI(); // does the extra checking required for validation of URI
I you dont want to do it programmatically, you can manipulate to the Column width property, which is located inside the Columns property.Once you open the column edit property you can choose which column you want to edit, scroll down to layout section of the bound column properties and change the width.
If SDK Setup.exe fails, please try to open a command-prompt and run "tools\android.bat" manually. That's all what SDK Setup does, however the current version has a bug in that it doesn't display errors that the batch might output:
> cd <your-sdk>\tools
> android.bat
That way you may see a more useful error message.
You must have a java.exe on your %PATH%.
In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:
public class CustomRunner extends BlockJUnit4ClassRunner {
public CTRunner(Class<?> klass) throws initializationError {
super(klass);
}
@Override
protected boolean isIgnored(FrameworkMethod child) {
if(shouldIgnore()) {
return true;
}
return super.isIgnored(child);
}
private boolean shouldIgnore(class) {
/* some custom criteria */
}
}
In my case, none the solutions above works. I have to checkout my source code to another folder. From eclipse select File > Switch workSpaces > Other... and then import code to the new workspaces. it works after that.
I don't have a windows box handy to try this but I think you can use a DataView and do something like so:
DataView view = new DataView(ds.Tables["MyTable"]);
view.RowFilter = "MyValue = 42"; // MyValue here is a column name
// Delete these rows.
foreach (DataRowView row in view)
{
row.Delete();
}
I haven't tested this, though. You might give it a try.
1: Create a custom attribute and override method like this:
public class CultureAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Retreive culture from GET
string currentCulture = filterContext.HttpContext.Request.QueryString["culture"];
// Also, you can retreive culture from Cookie like this :
//string currentCulture = filterContext.HttpContext.Request.Cookies["cookie"].Value;
// Set culture
Thread.CurrentThread.CurrentCulture = new CultureInfo(currentCulture);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(currentCulture);
}
}
2: In App_Start, find FilterConfig.cs, add this attribute. (this works for WHOLE application)
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// Add custom attribute here
filters.Add(new CultureAttribute());
}
}
That's it !
If you want to define culture for each controller/action in stead of whole application, you can use this attribute like this:
[Culture]
public class StudentsController : Controller
{
}
Or:
[Culture]
public ActionResult Index()
{
return View();
}
How about the Live method?
$('.add_to_this a').live('click', function() {
alert('hello from binded function call');
});
Still, what you did about looks like it should work. There's another post that looks pretty similar.
Doubt it was a "guru" who'd had any experience in high traffic...
Websites are usually "dirty" by the time the person is viewing the completely loaded page. Consider a form that loads from the database and then saves the data that's edited?? It's idiotic the way people go on about dirty reads being such a no no.
That said, if you have a number of layers building on your selects, you could be building in a dangerous redundancy. If you're dealing in money or status scenarios, then you need not only transactional data read/writes, but a proper concurrency solution (something most "gurus" don't bother with).
On the other hand, if you have an advanced product search for a website (ie something that likely won't be cached and be a little intensive) and you've ever built a site with more than a few concurrent users (phenominal how many "experts" haven't), it is rediculous to bottle neck every other process behind it.
Know what it means and use it when appropriate. Your database will almost always be your main bottle neck these days and being smart about using NOLOCK can save you thousands in infrastructure.
EDIT: It's not just deadlocks it helps with, it's also how much you are going to make everybody else wait until you're finished, or vice versa.
Set following before you openConnection,
System.setProperty("http.proxyHost", "host");
System.setProperty("http.proxyPort", "port_number");
If proxy requires authentication,
System.setProperty("http.proxyUser", "user");
System.setProperty("http.proxyPassword", "password");
I've heard good things about Eigen and NT2, but haven't personally used either. There's also Boost.UBLAS, which I believe is getting a bit long in the tooth. The developers of NT2 are building the next version with the intention of getting it into Boost, so that might count for somthing.
My lin. alg. needs don't exteed beyond the 4x4 matrix case, so I can't comment on advanced functionality; I'm just pointing out some options.
I had some trouble similar to this,
<repository>
<id>java.net</id>
<url>https://maven-repository.dev.java.net/nonav/repository</url>
<layout>legacy</layout>
</repository>
<repository>
<id>java.net2</id>
<url>https://maven2-repository.dev.java.net/nonav/repository</url>
</repository>
Setting the updatePolicy to "never" did not work. Removing these repo was the way I solved it. ps: I was following this tutorial about web services (btw, probably the best tutorial for ws for java)
When doing a clean HTML Structure, you can use this.
//Jquery Code_x000D_
$('a#link_1').click(function(e){_x000D_
e . preventDefault () ;_x000D_
var a = e . target ;_x000D_
window . open ( '_top' , a . getAttribute ('href') ) ;_x000D_
});_x000D_
_x000D_
//Normal Code_x000D_
element = document . getElementById ( 'link_1' ) ;_x000D_
element . onClick = function (e) {_x000D_
e . preventDefault () ;_x000D_
_x000D_
window . open ( '_top' , element . getAttribute ('href') ) ;_x000D_
} ;
_x000D_
<a href="#Foo" id="link_1">Do it!</a>
_x000D_
Use tiles. It saved my life.
But if you can't, there's the include tag, making it similar to php.
The body tag might not actually do what you need it to, unless you have super simple content. The body tag is used to define the body of a specified element. Take a look at this example:
<jsp:element name="${content.headerName}"
xmlns:jsp="http://java.sun.com/JSP/Page">
<jsp:attribute name="lang">${content.lang}</jsp:attribute>
<jsp:body>${content.body}</jsp:body>
</jsp:element>
You specify the element name, any attributes that element might have ("lang" in this case), and then the text that goes in it--the body. So if
content.headerName = h1
,content.lang = fr
, andcontent.body = Heading in French
Then the output would be
<h1 lang="fr">Heading in French</h1>
Since the static method 'GetAccessControl' seems to be missing from the present version of .Net core/Standard I had to modify @Bryce Wagner's answer (I went ahead and used more modern syntax):
public static class PermissionHelper
{
public static bool? CurrentUserHasWritePermission(string filePath)
=> new WindowsPrincipal(WindowsIdentity.GetCurrent())
.SelectWritePermissions(filePath)
.FirstOrDefault();
private static IEnumerable<bool?> SelectWritePermissions(this WindowsPrincipal user, string filePath)
=> from rule in filePath
.GetFileSystemSecurity()
.GetAccessRules(true, true, typeof(NTAccount))
.Cast<FileSystemAccessRule>()
let right = user.HasRightSafe(rule)
where right.HasValue
// Deny takes precedence over allow
orderby right.Value == false descending
select right;
private static bool? HasRightSafe(this WindowsPrincipal user, FileSystemAccessRule rule)
{
try
{
return user.HasRight(rule);
}
catch
{
return null;
}
}
private static bool? HasRight(this WindowsPrincipal user,FileSystemAccessRule rule )
=> rule switch
{
{ FileSystemRights: FileSystemRights fileSystemRights } when (fileSystemRights &
(FileSystemRights.WriteData | FileSystemRights.Write)) == 0 => null,
{ IdentityReference: { Value: string value } } when value.StartsWith("S-1-") &&
!user.IsInRole(new SecurityIdentifier(rule.IdentityReference.Value)) => null,
{ IdentityReference: { Value: string value } } when value.StartsWith("S-1-") == false &&
!user.IsInRole(rule.IdentityReference.Value) => null,
{ AccessControlType: AccessControlType.Deny } => false,
{ AccessControlType: AccessControlType.Allow } => true,
_ => null
};
private static FileSystemSecurity GetFileSystemSecurity(this string filePath)
=> new FileInfo(filePath) switch
{
{ Exists: true } fileInfo => fileInfo.GetAccessControl(),
{ Exists: false } fileInfo => (FileSystemSecurity)fileInfo.Directory.GetAccessControl(),
_ => throw new Exception($"Check the file path, {filePath}: something's wrong with it.")
};
}
$.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};
$(document).on("rightclick", "div", function() {
console.log("hello");
return false;
});
This is compatible with the standards-based browsers, but will probably fail in IE. I'm providing it as a starting point. IE doesn't support DOM Range.
var editable = document.getElementById('editable'),
selection, range;
// Populates selection and range variables
var captureSelection = function(e) {
// Don't capture selection outside editable region
var isOrContainsAnchor = false,
isOrContainsFocus = false,
sel = window.getSelection(),
parentAnchor = sel.anchorNode,
parentFocus = sel.focusNode;
while(parentAnchor && parentAnchor != document.documentElement) {
if(parentAnchor == editable) {
isOrContainsAnchor = true;
}
parentAnchor = parentAnchor.parentNode;
}
while(parentFocus && parentFocus != document.documentElement) {
if(parentFocus == editable) {
isOrContainsFocus = true;
}
parentFocus = parentFocus.parentNode;
}
if(!isOrContainsAnchor || !isOrContainsFocus) {
return;
}
selection = window.getSelection();
// Get range (standards)
if(selection.getRangeAt !== undefined) {
range = selection.getRangeAt(0);
// Get range (Safari 2)
} else if(
document.createRange &&
selection.anchorNode &&
selection.anchorOffset &&
selection.focusNode &&
selection.focusOffset
) {
range = document.createRange();
range.setStart(selection.anchorNode, selection.anchorOffset);
range.setEnd(selection.focusNode, selection.focusOffset);
} else {
// Failure here, not handled by the rest of the script.
// Probably IE or some older browser
}
};
// Recalculate selection while typing
editable.onkeyup = captureSelection;
// Recalculate selection after clicking/drag-selecting
editable.onmousedown = function(e) {
editable.className = editable.className + ' selecting';
};
document.onmouseup = function(e) {
if(editable.className.match(/\sselecting(\s|$)/)) {
editable.className = editable.className.replace(/ selecting(\s|$)/, '');
captureSelection();
}
};
editable.onblur = function(e) {
var cursorStart = document.createElement('span'),
collapsed = !!range.collapsed;
cursorStart.id = 'cursorStart';
cursorStart.appendChild(document.createTextNode('—'));
// Insert beginning cursor marker
range.insertNode(cursorStart);
// Insert end cursor marker if any text is selected
if(!collapsed) {
var cursorEnd = document.createElement('span');
cursorEnd.id = 'cursorEnd';
range.collapse();
range.insertNode(cursorEnd);
}
};
// Add callbacks to afterFocus to be called after cursor is replaced
// if you like, this would be useful for styling buttons and so on
var afterFocus = [];
editable.onfocus = function(e) {
// Slight delay will avoid the initial selection
// (at start or of contents depending on browser) being mistaken
setTimeout(function() {
var cursorStart = document.getElementById('cursorStart'),
cursorEnd = document.getElementById('cursorEnd');
// Don't do anything if user is creating a new selection
if(editable.className.match(/\sselecting(\s|$)/)) {
if(cursorStart) {
cursorStart.parentNode.removeChild(cursorStart);
}
if(cursorEnd) {
cursorEnd.parentNode.removeChild(cursorEnd);
}
} else if(cursorStart) {
captureSelection();
var range = document.createRange();
if(cursorEnd) {
range.setStartAfter(cursorStart);
range.setEndBefore(cursorEnd);
// Delete cursor markers
cursorStart.parentNode.removeChild(cursorStart);
cursorEnd.parentNode.removeChild(cursorEnd);
// Select range
selection.removeAllRanges();
selection.addRange(range);
} else {
range.selectNode(cursorStart);
// Select range
selection.removeAllRanges();
selection.addRange(range);
// Delete cursor marker
document.execCommand('delete', false, null);
}
}
// Call callbacks here
for(var i = 0; i < afterFocus.length; i++) {
afterFocus[i]();
}
afterFocus = [];
// Register selection again
captureSelection();
}, 10);
};
Try this:
using System.ComponentModel;
youtItemsControl.Items.SortDescriptions.Add(new SortDescription("yourFavoritePropertyFromItem",ListSortDirection.Ascending);
Here is a list of commercial vendors that provide off-the-shelf packages for facial recognition which run on Windows:
Cybula - Information on their Facial Recognition SDK. This is a company founded by a University Professor and as such their website looks unprofessional. There's no pricing information or demo that you can download. You'll need to contact them for pricing information.
NeuroTechnology - Information on their Facial Recognition SDK. This company has both up-front pricing information as well as an actual 30 day trial of their SDK.
Pittsburgh Pattern Recognition - (Acquired by Google) Information on their Facial Tracking and Recognition SDK. The demos that they provide help you evaluate their technology but not their SDSK. You'll need to contact them for pricing information.
Sensible Vision - Information on their SDK. Their site allows you to easily get a price quote and you can also order an evaluation kit that will help you evaluate their technology.
libcurl also provides CURLOPT_COOKIELIST which extracts all known cookies. All you need is to make sure the PHP/CURL binding can use it.
Wouldn't
(int) Math.Min(Int32.MaxValue, longValue)
be the correct way, mathematically speaking?
C style, simple ring buffer for integers. First use init than use put and get. If buffer does not contain any data it returns "0" zero.
//=====================================
// ring buffer address based
//=====================================
#define cRingBufCount 512
int sRingBuf[cRingBufCount]; // Ring Buffer
int sRingBufPut; // Input index address
int sRingBufGet; // Output index address
Bool sRingOverWrite;
void GetRingBufCount(void)
{
int r;
` r= sRingBufPut - sRingBufGet;
if ( r < cRingBufCount ) r+= cRingBufCount;
return r;
}
void InitRingBuffer(void)
{
sRingBufPut= 0;
sRingBufGet= 0;
}
void PutRingBuffer(int d)
{
sRingBuffer[sRingBufPut]= d;
if (sRingBufPut==sRingBufGet)// both address are like ziro
{
sRingBufPut= IncRingBufferPointer(sRingBufPut);
sRingBufGet= IncRingBufferPointer(sRingBufGet);
}
else //Put over write a data
{
sRingBufPut= IncRingBufferPointer(sRingBufPut);
if (sRingBufPut==sRingBufGet)
{
sRingOverWrite= Ture;
sRingBufGet= IncRingBufferPointer(sRingBufGet);
}
}
}
int GetRingBuffer(void)
{
int r;
if (sRingBufGet==sRingBufPut) return 0;
r= sRingBuf[sRingBufGet];
sRingBufGet= IncRingBufferPointer(sRingBufGet);
sRingOverWrite=False;
return r;
}
int IncRingBufferPointer(int a)
{
a+= 1;
if (a>= cRingBufCount) a= 0;
return a;
}
I know this isn't a 'replacement' WebBrowser control, but I was having some awful rendering issues whilst showing a page that was using BootStrap 3+ for layout etc, and then I found a post that suggested I use the following. Apparently, it's specific to IE and tells it to use the latest variation found on the client machine for rendering (so it won't use IE7, which I believe is the default).
So just put:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
somewhere in the head part of your document.
Obviously, if it's not your document, this won't help - though I personally consider it to be a security hole if you're reading pages not created by yourself through the WebBrowser control - why not just use a web browser!
document.addEventListener('paste', function(e){
if(e.clipboardData.types.indexOf('text/html') > -1){
processDataFromClipboard(e.clipboardData.getData('text/html'));
e.preventDefault();
...
}
});
I needed this as well, and with the help of Bombe's answer + some fiddling around, I got it working. Here's the recipe:
1. cd /path/to/git/localrepo
2. svn mkdir --parents protocol:///path/to/repo/PROJECT/trunk -m "Importing git repo"
3. git svn init protocol:///path/to/repo/PROJECT -s
4. git svn fetch
5. git rebase origin/trunk
5.1. git status
5.2. git add (conflicted-files)
5.3. git rebase --continue
5.4. (repeat 5.1.)
6. git svn dcommit
After #3 you'll get a cryptic message like this:
Using higher level of URL:
protocol:///path/to/repo/PROJECT => protocol:///path/to/repo
Just ignore that.
When you run #5, you might get conflicts. Resolve these by adding files with state "unmerged" and resuming rebase. Eventually, you'll be done; then sync back to the SVN repository, using dcommit
. That's all.
You can now synchronise from SVN to Git, using the following commands:
git svn fetch
git rebase trunk
And to synchronise from Git to SVN, use:
git svn dcommit
You might want to try this out on a local copy, before applying to a live repository. You can make a copy of your Git repository to a temporary place; simply use cp -r
, as all data is in the repository itself. You can then set up a file-based testing repository, using:
svnadmin create /home/name/tmp/test-repo
And check a working copy out, using:
svn co file:///home/name/tmp/test-repo svn-working-copy
That'll allow you to play around with things before making any lasting changes.
git svn init
If you accidentally run git svn init
with the wrong URL, and you weren't smart enough to take a backup of your work (don't ask ...), you can't just run the same command again. You can however undo the changes by issuing:
rm -rf .git/svn
edit .git/config
And remove the section [svn-remote "svn"]
section.
You can then run git svn init
anew.
In my case, there is a single table which happens to be a device list from a router. If you wish to read the table using TR/TH/TD (row, header, data) instead of a matrix as mentioned above, you can do something like the following:
List<TableRow> deviceTable = (from table in document.DocumentNode.SelectNodes(XPathQueries.SELECT_TABLE)
from row in table?.SelectNodes(HtmlBody.TR)
let rows = row.SelectSingleNode(HtmlBody.TR)
where row.FirstChild.OriginalName != null && row.FirstChild.OriginalName.Equals(HtmlBody.T_HEADER)
select new TableRow
{
Header = row.SelectSingleNode(HtmlBody.T_HEADER)?.InnerText,
Data = row.SelectSingleNode(HtmlBody.T_DATA)?.InnerText}).ToList();
}
TableRow is just a simple object with Header and Data as properties. The approach takes care of null-ness and this case:
<tr>_x000D_
<td width="28%"> </td>_x000D_
</tr>
_x000D_
which is row without a header. The HtmlBody object with the constants hanging off of it are probably readily deduced but I apologize for it even still. I came from the world where if you have " in your code, it should either be constant or localizable.
As @jem suggested, it is possible to use jsoup.
With jSoup 1.8.3 it il possible to use the method Parser.unescapeEntities that retain the original html.
import org.jsoup.parser.Parser;
...
String html = Parser.unescapeEntities(original_html, false);
It seems that in some previous release this method is not present.
In situations like this, why not write your own? A simple server app to test connections can be done in a matter of minutes if you know what you're doing, and you can make it respond exactly how you need to, and for specific scenarios.
You can extract method:
public int cmp(String txt, String otherTxt)
{
if ( txt == null )
return otjerTxt == null ? 0 : 1;
if ( otherTxt == null )
return 1;
return txt.compareToIgnoreCase(otherTxt);
}
public int compareTo(Metadata other) {
int result = cmp( name, other.name);
if ( result != 0 ) return result;
return cmp( value, other.value);
}
To alter a stored procedure, here's the C# code:
SqlConnection con = new SqlConnection("your connection string");
con.Open();
cmd.CommandType = System.Data.CommandType.Text;
string sql = File.ReadAllText(YUOR_SP_SCRIPT_FILENAME);
cmd.CommandText = sql;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
Things to note:
GO,SET ANSI_NULLS XX,SET QUOTED_IDENTIFIER
statements from the script file. (If you don't, the SqlCommand will throw an error).If one is using Maven Build from the command prompt one can use the following command as well:
mvn -Dproject.build.sourceEncoding=UTF-8
With Git there is no “correct” workflow. Use whatever floats your boat. However, if you constantly get conflicts when merging branches maybe you should coordinate your efforts better with your fellow developer(s)? Sounds like the two of you keep editing the same files. Also, watch out for whitespace and subversion keywords (i.e., “$Id$” and others).
Building on Olie and Algal's answer, here is an updated answer for Swift 3
public func getRGBAs(fromImage image: UIImage, x: Int, y: Int, count: Int) -> [UIColor] {
var result = [UIColor]()
// First get the image into your data buffer
guard let cgImage = image.cgImage else {
print("CGContext creation failed")
return []
}
let width = cgImage.width
let height = cgImage.height
let colorSpace = CGColorSpaceCreateDeviceRGB()
let rawdata = calloc(height*width*4, MemoryLayout<CUnsignedChar>.size)
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
guard let context = CGContext(data: rawdata, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
print("CGContext creation failed")
return result
}
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
// Now your rawData contains the image data in the RGBA8888 pixel format.
var byteIndex = bytesPerRow * y + bytesPerPixel * x
for _ in 0..<count {
let alpha = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 3, as: UInt8.self)) / 255.0
let red = CGFloat(rawdata!.load(fromByteOffset: byteIndex, as: UInt8.self)) / alpha
let green = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 1, as: UInt8.self)) / alpha
let blue = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 2, as: UInt8.self)) / alpha
byteIndex += bytesPerPixel
let aColor = UIColor(red: red, green: green, blue: blue, alpha: alpha)
result.append(aColor)
}
free(rawdata)
return result
}
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
Here's an example using Guzzle:
/**
* @param string $accessToken JSON-encoded access token as returned by \Google_Client->getAccessToken() or raw access token
* @return array|false False if token is invalid or array in the form
*
* array (
* 'issued_to' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
* 'audience' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
* 'scope' => 'https://www.googleapis.com/auth/calendar',
* 'expires_in' => 3350,
* 'access_type' => 'offline',
* )
*/
public static function tokenInfo($accessToken) {
if(!strlen($accessToken)) {
return false;
}
if($accessToken[0] === '{') {
$accessToken = json_decode($accessToken)->access_token;
}
$guzzle = new \GuzzleHttp\Client();
try {
$resp = $guzzle->get('https://www.googleapis.com/oauth2/v1/tokeninfo', [
'query' => ['access_token' => $accessToken],
]);
} catch(ClientException $ex) {
return false;
}
return $resp->json();
}
If you don't want to get involved with locales here is a function that formats numbers:
def int_format(value, decimal_points=3, seperator=u'.'):
value = str(value)
if len(value) <= decimal_points:
return value
# say here we have value = '12345' and the default params above
parts = []
while value:
parts.append(value[-decimal_points:])
value = value[:-decimal_points]
# now we should have parts = ['345', '12']
parts.reverse()
# and the return value should be u'12.345'
return seperator.join(parts)
Creating a custom template filter from this function is trivial.
sometimes there's a difference between the local cached version of origin master (origin/master) and the true origin master.
If you run git remote update
this will resynch origin master with origin/master
see the accepted answer to this question
Differences between git pull origin master & git pull origin/master
I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement
.
/(.+)/(\d{4}-\d{2}-\d{2})-(\d+)(/.*)?$
1st Capturing Group (.+)
.+
matches any character (except for line terminators)
+
Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)2nd Capturing Group (\d{4}-\d{2}-\d{2})
\d{4}
matches a digit (equal to [0-9]
)
{4}
Quantifier — Matches exactly 4 times-
matches the character -
literally (case sensitive)
\d{2}
matches a digit (equal to [0-9]
)
{2}
Quantifier — Matches exactly 2 times-
matches the character -
literally (case sensitive)
\d{2}
matches a digit (equal to [0-9]
)
{2}
Quantifier — Matches exactly 2 times-
matches the character -
literally (case sensitive)
3rd Capturing Group (\d+)
\d+
matches a digit (equal to [0-9]
)
+
Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)4th Capturing Group (.*)?
?
Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
.*
matches any character (except for line terminators)
*
Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)$
asserts position at the end of the string
The c
variable already contains the char code!
"string".each_byte do |c|
puts c
end
yields
115
116
114
105
110
103
Here is a benchmark showing that using str.lower
is faster than the accepted answer's proposed method (libc.strcasecmp
):
#!/usr/bin/env python2.7
import random
import timeit
from ctypes import *
libc = CDLL('libc.dylib') # change to 'libc.so.6' on linux
with open('/usr/share/dict/words', 'r') as wordlist:
words = wordlist.read().splitlines()
random.shuffle(words)
print '%i words in list' % len(words)
setup = 'from __main__ import words, libc; gc.enable()'
stmts = [
('simple sort', 'sorted(words)'),
('sort with key=str.lower', 'sorted(words, key=str.lower)'),
('sort with cmp=libc.strcasecmp', 'sorted(words, cmp=libc.strcasecmp)'),
]
for (comment, stmt) in stmts:
t = timeit.Timer(stmt=stmt, setup=setup)
print '%s: %.2f msec/pass' % (comment, (1000*t.timeit(10)/10))
typical times on my machine:
235886 words in list
simple sort: 483.59 msec/pass
sort with key=str.lower: 1064.70 msec/pass
sort with cmp=libc.strcasecmp: 5487.86 msec/pass
So, the version with str.lower
is not only the fastest by far, but also the most portable and pythonic of all the proposed solutions here.
I have not profiled memory usage, but the original poster has still not given a compelling reason to worry about it. Also, who says that a call into the libc module doesn't duplicate any strings?
NB: The lower()
string method also has the advantage of being locale-dependent. Something you will probably not be getting right when writing your own "optimised" solution. Even so, due to bugs and missing features in Python, this kind of comparison may give you wrong results in a unicode context.
Most IDEs present the project structure in a top down manner. This is great way to explore at a high level when joining an existing project. However, after working on the same project for more than a year, I realized that this approach can become counter-productive.
After Oracle declared the end of Ruby in NetBeans, I switched to Vim. By using a command line and an editor as the only tools, I was forced to mentally switch to a bottom-up perspective. To my amazement, I discovered that this made me more focused and productive. As a bonus, I got first class HAML and SASS syntax support.
I recommend Vim + Rails plugin for anyone that will work on a single project for an extended period of time.
Codeslave asks "Shouldn't it always be "$ORACLE_ HOME/network/admin/tnsnames.ora"? The answer is no, it isn't. Consider these two invocations of tnsping on the same machine:
C:\Documents and Settings\me>D:\Oracle\10.2.0_DB\BIN\tnsping orcl
TNS Ping Utility for 32-bit Windows: Version 10.2.0.4.0 - Production on 09-OCT-2
008 14:30:12
Copyright (c) 1997, 2007, Oracle. All rights reserved.
Used parameter files:
D:\Oracle\10.2.0_DB\network\admin\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = xxxx
)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = ORCL)))
OK (40 msec)
C:\Documents and Settings\me>tnsping orcl
TNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 09-OCT-2
008 14:30:21
Copyright (c) 1997, 2005, Oracle. All rights reserved.
Used parameter files:
D:\oracle\10.2.0_Client\network\admin\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)
(HOST = XXXX)(PORT = 1521))) (CONNECT_DATA = (SERVICE_NAME = ORCL)))
OK (20 msec)
C:\Documents and Settings\me>
Note the two different parameter file locations, that are dependent on which tnsping executable you're running (and perhaps where it's being run from). For tnsnames-based oracle networking, using the TNS_ADMIN variable is the only way to ensure you're getting a consistent tnsnames.ora file. (NOTE: Windows-centric answer)
if you want to stay DRY, use an include.
{% if foo %}
{% with a as b %}
{% include "snipet.html" %}
{% endwith %}
{% else %}
{% with bar as b %}
{% include "snipet.html" %}
{% endwith %}
{% endif %}
or, even better would be to write a method on the model that encapsulates the core logic:
def Patient(models.Model):
....
def get_legally_responsible_party(self):
if self.age > 18:
return self
else:
return self.parent
Then in the template:
{% with patient.get_legally_responsible_party as p %}
Do html stuff
{% endwith %}
Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.
You can convert BigDecimal
to double
using .doubleValue()
. But believe me, don't use it if you have currency manipulations. It should always be performed on BigDecimal
objects directly. Precision loss in these calculations are big time problems in currency related calculations.
I have made this function. It works fine but returns string.
function show_float_val(val,upto = 2){
var val = parseFloat(val);
return val.toFixed(upto);
}
You could utilize jQuery.filter() function to return elements from a subset of the matching elements.
var names = [_x000D_
{ name : "Joe", age:20, email: "[email protected]"},_x000D_
{ name : "Mike", age:50, email: "[email protected]"},_x000D_
{ name : "Joe", age:45, email: "[email protected]"}_x000D_
];_x000D_
_x000D_
_x000D_
var filteredNames = $(names).filter(function( idx ) {_x000D_
return names[idx].name === "Joe" && names[idx].age < 30;_x000D_
}); _x000D_
_x000D_
$(filteredNames).each(function(){_x000D_
$('#output').append(this.name);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="output"/>
_x000D_
Here is a great article using Restkit
It explains on serializing nested data into JSON and attaching the data to a HTTP POST request.
$(".show-pass").click(function (e) {_x000D_
e.preventDefault();_x000D_
var type = $("#signupform-password").attr('type');_x000D_
switch (type) {_x000D_
case 'password':_x000D_
{_x000D_
$("#signupform-password").attr('type', 'text');_x000D_
return;_x000D_
}_x000D_
case 'text':_x000D_
{_x000D_
$("#signupform-password").attr('type', 'password');_x000D_
return;_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" name="password" class="show-pass">
_x000D_
Below code works for me in Angular 4
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class RegisterComponent implements OnInit {
registerForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
empname: [''],
empemail: ['']
});
}
onRegister(){
//sending data to server using http request
this.registerForm.reset()
}
}
If somebody needs this solution in Swift 5:
private func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
image.draw(in:CGRect(x:0, y:0, width:newWidth, height:newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
I'm using Oh-my-zsh
in my macbook so I've tried many things to get the crontab task runs but finally, my solution was prepending the .zshrc
before the command to run.
*/30 * * * * . $HOME/.zshrc; node /path/for/my_script.js
This task runs every 30 minutes and uses .zshrc
profile to execute my node command.
Don't forget to use the dot before the $HOME
var.
Changed to:
SELECT FORMAT(SA.[RequestStartDate],'dd/MM/yyyy') as 'Service Start Date', SA.[RequestEndDate] as 'Service End Date', FROM (......)SA WHERE......
Have no idea which SQL engine you are using, for other SQL engine, CONVERT can be used in SELECT statement to change the format in the form you needed.
Jersey needs to be unpacked jars.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<requiresUnpack>
<dependency>
<groupId>com.myapp</groupId>
<artifactId>rest-api</artifactId>
</dependency>
</requiresUnpack>
</configuration>
</plugin>
</plugins>
</build>
You can easily call any controller's action using jQuery AJAX method like this:
Note in this example my controller name is Student
Controller Action
public ActionResult Test()
{
return View();
}
In Any View of this above controller you can call the Test() action like this:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "@Url.Action("Test", "Student")",
success: function (result, status, xhr) {
alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
},
error: function (xhr, status, error) {
alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
});
</script>
You can also use the split()
function. This seems to be the easiest one that comes to my mind :).
url.split('?')[0]
One advantage is this method will work even if there is no ?
in the string - it will return the whole string.
This error happens on your side and NOT the other side. If the other side reset the connection, then the exception message should say:
java.net.SocketException reset by peer
The cause is the connection inside HttpClient
is stale. Check stale connection for SSL does not fix this error. Solution: dump your client and recreate.
I've tried few methods from this question and they all failed on my CentOs, either because of the wrong repos or missing files.
Here is the method which works for me (when installing version 1.7.8):
yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
wget http://git-core.googlecode.com/files/git-1.7.8.tar.gz
tar -xzvf ./git-1.7.8.tar.gz
cd ./git-1.7.8
./configure
make
make install
You may want to download a different version from here: http://code.google.com/p/git-core/downloads/list
As mentioned here, https://stackoverflow.com/a/50941562/2186220, use gradle plugin version 3 or higher while using 'implementation'.
Also, use the google()
repository in buildscript
.
buildscript {
repositories {
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
}
}
These changes should solve the issue.
protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RemoveAt = gvr.RowIndex;
DataTable dt = new DataTable();
dt = (DataTable)ViewState["Products"];
dt.Rows.RemoveAt(RemoveAt);
dt.AcceptChanges();
ViewState["Products"] = dt;
}
}
catch (Exception ex)
{
throw;
}
}
protected void gvProductsList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
gvProductsList.DataSource = ViewState["Products"];
gvProductsList.DataBind();
}
catch (Exception ex)
{
}
}
A good solution can be one provided by @Elias Van Ootegan
in a comment that is:
$ids = array_column($array, 'id', 'id');
echo isset($ids[40489])?"Exist":"Not Exist";
I tried it and worked for me, thanks buddy.
Edited
Note: It will work in PHP 5.5+
Given the string foobarbarfoo
:
bar(?=bar) finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar) finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar finds the 2nd bar ("bar" which does not have "foo" before it)
You can also combine them:
(?<=foo)bar(?=bar) finds the 1st bar ("bar" with "foo" before it and "bar" after it)
(?=)
Find expression A where expression B follows:
A(?=B)
(?!)
Find expression A where expression B does not follow:
A(?!B)
(?<=)
Find expression A where expression B precedes:
(?<=B)A
(?<!)
Find expression A where expression B does not precede:
(?<!B)A
(?>)
An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).
(?>foo|foot)s
applied to foots
will match its 1st alternative foo
, then fail as s
does not immediately follow, and stop as backtracking is disabledA non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.
(foo|foot)s
applied to foots
will:
foo
, then fail as s
does not immediately follow in foots
, and backtrack to its 2nd alternative;foot
, then succeed as s
immediately follows in foots
, and stop.<input type="text" value="Your value">
Use the value
attribute for the pre filled in values.
In mongodb 3.0 or above, we can specify database name to restore. Assuming that you are standing at the root directory that contains bson files
./
a.bson
b.metadata.bson
...
The script would be
for FILENAME in *; do mongorestore -d <db_name> -c "${FILENAME%.*}" $FILENAME; done
Best,
If you have a problem with dependencies when download a new version, try...
FILE....MANAGE IDE SETTINGS...RESTORE DEFAULT SETTINGS
Si tienes un problema con las dependencias cuando actualizas a una nueva versión..intenta..
FILE..MANAGE IDE SETTINGS...RESTORE DEFAULT SETTINGS
I'm surprised that no one has mentioned the list-style-image property
ul {
list-style-image: url('images/ico-list-bullet.png');
}
When you provide no arguments to go install
, it defaults to attempting to install the package in the current directory. The error message is telling you that it cannot do that, because the current directory isn't part of your $GOPATH
.
You can either:
$GOPATH
to your $HOME (export GOPATH=$HOME
).$GOPATH
(mv ~/src/go-statsd-client /User/me/gopath
).After either, going into the go-statsd-client
directory and typing go install
will work, and so will typing go install go-statsd-client
from anywhere in the filesystem. The built binaries will go into $GOPATH/bin
.
As an unrelated suggestion, you probably want to namespace your package with a domain name, to avoid name clashing (e.g. github.com/you/go-statsd-client
, if that's where you hold your source code).
Imagine having this hierarchy
By writing
List<? extends C2> list;
you are saying that list
will be able to reference an object of type (for example) ArrayList
whose generic type is one of the 7 subtypes of C2
(C2
included):
new ArrayList<C2>();
, (an object that can store C2 or subtypes) ornew ArrayList<D1>();
, (an object that can store D1 or subtypes) ornew ArrayList<D2>();
, (an object that can store D2 or subtypes) or...and so on. Seven different cases:
1) new ArrayList<C2>(): can store C2 D1 D2 E1 E2 E3 E4
2) new ArrayList<D1>(): can store D1 E1 E2
3) new ArrayList<D2>(): can store D2 E3 E4
4) new ArrayList<E1>(): can store E1
5) new ArrayList<E2>(): can store E2
6) new ArrayList<E3>(): can store E3
7) new ArrayList<E4>(): can store E4
We have a set of "storable" types for each possible case: 7 (red) sets here graphically represented
As you can see, there is not a safe type that is common to every case:
list.add(new C2(){});
because it could be list = new ArrayList<D1>();
list.add(new D1(){});
because it could be list = new ArrayList<D2>();
and so on.
By writing
List<? super C2> list;
you are saying that list
will be able to reference an object of type (for example) ArrayList
whose generic type is one of the 7 supertypes of C2
(C2
included):
new ArrayList<A1>();
, (an object that can store A1 or subtypes) ornew ArrayList<A2>();
, (an object that can store A2 or subtypes) ornew ArrayList<A3>();
, (an object that can store A3 or subtypes) or...and so on. Seven different cases:
1) new ArrayList<A1>(): can store A1 B1 B2 C1 C2 D1 D2 E1 E2 E3 E4
2) new ArrayList<A2>(): can store A2 B2 C1 C2 D1 D2 E1 E2 E3 E4
3) new ArrayList<A3>(): can store A3 B3 C2 C3 D1 D2 E1 E2 E3 E4
4) new ArrayList<A4>(): can store A4 B3 B4 C2 C3 D1 D2 E1 E2 E3 E4
5) new ArrayList<B2>(): can store B2 C1 C2 D1 D2 E1 E2 E3 E4
6) new ArrayList<B3>(): can store B3 C2 C3 D1 D2 E1 E2 E3 E4
7) new ArrayList<C2>(): can store C2 D1 D2 E1 E2 E3 E4
We have a set of "storable" types for each possible case: 7 (red) sets here graphically represented
As you can see, here we have seven safe types that are common to every case: C2
, D1
, D2
, E1
, E2
, E3
, E4
.
list.add(new C2(){});
because, regardless of the kind of List we're referencing, C2
is allowedlist.add(new D1(){});
because, regardless of the kind of List we're referencing, D1
is allowedand so on. You probably noticed that these types correspond to the hierarchy starting from type C2
.
Here the complete hierarchy if you wish to make some tests
interface A1{}
interface A2{}
interface A3{}
interface A4{}
interface B1 extends A1{}
interface B2 extends A1,A2{}
interface B3 extends A3,A4{}
interface B4 extends A4{}
interface C1 extends B2{}
interface C2 extends B2,B3{}
interface C3 extends B3{}
interface D1 extends C1,C2{}
interface D2 extends C2{}
interface E1 extends D1{}
interface E2 extends D1{}
interface E3 extends D2{}
interface E4 extends D2{}
It will use to make menu bar in directory format
$pathLen = 0;
function prePad($level)
{
$ss = "";
for ($ii = 0; $ii < $level; $ii++)
{
$ss = $ss . "| ";
}
return $ss;
}
function myScanDir($dir, $level, $rootLen)
{
global $pathLen;
if ($handle = opendir($dir)) {
$allFiles = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($dir . "/" . $entry))
{
$allFiles[] = "D: " . $dir . "/" . $entry;
}
else
{
$allFiles[] = "F: " . $dir . "/" . $entry;
}
}
}
closedir($handle);
natsort($allFiles);
foreach($allFiles as $value)
{
$displayName = substr($value, $rootLen + 4);
$fileName = substr($value, 3);
$linkName = str_replace(" ", " ", substr($value, $pathLen + 3));
if (is_dir($fileName))
{
echo "<li ><a class='dropdown'><span>" . $displayName . " </span></a><ul>";
myScanDir($fileName, $level + 1, strlen($fileName));
echo "</ul></li>";
}
else {
$newstring = substr($displayName, -3);
if($newstring == "PDF" || $newstring == "pdf" )
echo "<li ><a href=\"" . $linkName . "\" style=\"text-decoration:none;\">" . $displayName . "</a></li>";
}
$t;
if($level != 0)
{
if($level < $t)
{
$r = int($t) - int($level);
for($i=0;$i<$r;$i++)
{
echo "</ul></li>";
}
}
}
$t = $level;
}
}
}
?>
<li style="color: #ffffff">
<?php
// ListFolder('D:\PDF');
$root = 'D:\PDF';
$pathLen = strlen($root);
myScanDir($root, 0, strlen($root));
?>
</li>
I use:
ls -ABrt1 --group-directories-first | tail -n1
It gives me just the file name, excluding folders.
In order to reuse a single confirmation dialog implementation in a multi-module application, the dialog must be implemented in a separate module. Here's one way of doing this with Material Design and FxFlex, though both of those can be trimmed back or replaced.
First the shared module (./app.module.ts):
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {MatDialogModule, MatSelectModule} from '@angular/material';
import {ConfirmationDlgComponent} from './confirmation-dlg.component';
import {FlexLayoutModule} from '@angular/flex-layout';
@NgModule({
imports: [
CommonModule,
FlexLayoutModule,
MatDialogModule
],
declarations: [
ConfirmationDlgComponent
],
exports: [
ConfirmationDlgComponent
],
entryComponents: [ConfirmationDlgComponent]
})
export class SharedModule {
}
And the dialog component (./confirmation-dlg.component.ts):
import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA} from '@angular/material';
@Component({
selector: 'app-confirmation-dlg',
template: `
<div fxLayoutAlign="space-around" class="title colors" mat-dialog-title>{{data.title}}</div>
<div class="msg" mat-dialog-content>
{{data.msg}}
</div>
<a href="#"></a>
<mat-dialog-actions fxLayoutAlign="space-around">
<button mat-button [mat-dialog-close]="false" class="colors">No</button>
<button mat-button [mat-dialog-close]="true" class="colors">Yes</button>
</mat-dialog-actions>`,
styles: [`
.title {font-size: large;}
.msg {font-size: medium;}
.colors {color: white; background-color: #3f51b5;}
button {flex-basis: 60px;}
`]
})
export class ConfirmationDlgComponent {
constructor(@Inject(MAT_DIALOG_DATA) public data: any) {}
}
Then we can use it in another module:
import {FlexLayoutModule} from '@angular/flex-layout';
import {NgModule} from '@angular/core';
import {GeneralComponent} from './general/general.component';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {CommonModule} from '@angular/common';
import {MaterialModule} from '../../material.module';
@NgModule({
declarations: [
GeneralComponent
],
imports: [
FlexLayoutModule,
MaterialModule,
CommonModule,
NgbModule.forRoot()
],
providers: []
})
export class SystemAdminModule {}
The component's click handler uses the dialog:
import {Component} from '@angular/core';
import {ConfirmationDlgComponent} from '../../../shared/confirmation-dlg.component';
import {MatDialog} from '@angular/material';
@Component({
selector: 'app-general',
templateUrl: './general.component.html',
styleUrls: ['./general.component.css']
})
export class GeneralComponent {
constructor(private dialog: MatDialog) {}
onWhateverClick() {
const dlg = this.dialog.open(ConfirmationDlgComponent, {
data: {title: 'Confirm Whatever', msg: 'Are you sure you want to whatever?'}
});
dlg.afterClosed().subscribe((whatever: boolean) => {
if (whatever) {
this.whatever();
}
});
}
whatever() {
console.log('Do whatever');
}
}
Just using the this.modal.open(MyComponent);
as you did won't return you an object whose events you can subscribe to which is why you can't get it to do something. This code creates and opens a dialog whose events we can subscribe to.
If you trim back the css and html this is really a simple component, but writing it yourself gives you control over its design and layout whereas a pre-written component will need to be much more heavyweight to give you that control.
In SQL, the 'WHERE' and 'ON' clause,are kind of Conditional Statemants, but the major difference between them are, the 'Where' Clause is used in Select/Update Statements for specifying the Conditions, whereas the 'ON' Clause is used in Joins, where it verifies or checks if the Records are Matched in the target and source tables, before the Tables are Joined
For Example: - 'WHERE'
SELECT * FROM employee WHERE employee_id=101
For Example: - 'ON'
There are two tables employee and employee_details, the matching columns are employee_id.
SELECT * FROM employee
INNER JOIN employee_details
ON employee.employee_id = employee_details.employee_id
Hope I have answered your Question. Revert for any clarifications.
You may use the jquery's Contents method to get the content of the iframe.
According to Reserved IP addresses there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are 3,706,452,992 public addresses.
And too many addresses in this post.
Alert will block the program flow so you can just write the following.
echo ("<script LANGUAGE='JavaScript'>
window.alert('Succesfully Updated');
window.location.href='http://someplace.com';
</script>");
I have found another way to read an image size (more generic). You can use ImageIO class in cooperation with ImageReaders. Here is the sample code:
private Dimension getImageDim(final String path) {
Dimension result = null;
String suffix = this.getFileSuffix(path);
Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
if (iter.hasNext()) {
ImageReader reader = iter.next();
try {
ImageInputStream stream = new FileImageInputStream(new File(path));
reader.setInput(stream);
int width = reader.getWidth(reader.getMinIndex());
int height = reader.getHeight(reader.getMinIndex());
result = new Dimension(width, height);
} catch (IOException e) {
log(e.getMessage());
} finally {
reader.dispose();
}
} else {
log("No reader found for given format: " + suffix));
}
return result;
}
Note that getFileSuffix is method that returns extension of path without "." so e.g.: png, jpg etc. Example implementation is:
private String getFileSuffix(final String path) {
String result = null;
if (path != null) {
result = "";
if (path.lastIndexOf('.') != -1) {
result = path.substring(path.lastIndexOf('.'));
if (result.startsWith(".")) {
result = result.substring(1);
}
}
}
return result;
}
This solution is very quick as only image size is read from the file and not the whole image. I tested it and there is no comparison to ImageIO.read performance. I hope someone will find this useful.
You may use:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
or
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.
Example: /src/main/java...
As above the question was originally about MySQL
Use REGEXP
, not LIKE
:
SELECT * FROM `table` WHERE ([url] NOT REGEXP '^[-A-Za-z0-9/.]+$')
I find it useful to turn an UPDATE into a SELECT to get the rows I want to update as a test before updating. If I can select the exact rows I want, I can update just those rows I want to update.
DECLARE @expense_report_id AS INT
SET @expense_report_id = 1027
--UPDATE expense_report_detail_distribution
--SET service_bill_id = 9
SELECT *
FROM expense_report_detail_distribution erdd
INNER JOIN expense_report_detail erd
INNER JOIN expense_report er
ON er.expense_report_id = erd.expense_report_id
ON erdd.expense_report_detail_id = erd.expense_report_detail_id
WHERE er.expense_report_id = @expense_report_id
In my case i have a main.py that have dependencies with other files. After I build that app with py installer using this command:
pyinstaller --onefile --windowed main.py
I got the main.exe inside dist folder. I double clicked on this file, and I raised the error mentioned above. To fix this, I just copy the main.exe from dist directory to previous directory, which is the root directory of my main.py and the dependency files, and I got no error after run the main.exe.
I made this codepen to help you out!
const navbar = document.querySelector('#nav')
window.addEventListener('scroll', function(e) {
const lastPosition = window.scrollY
if (lastPosition > 50 ) {
navbar.classList.add('active')
} else if (navbar.classList.contains('active')) {
navbar.classList.remove('active')
} else {
navbar.classList.remove('active')
}
})
VLookup
You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4".
External Reference
To reference a cell of the same Workbook use the following pattern:
<Sheetname>!<Cell>
Example:
Table1!A1
To reference a cell of a different Workbook use this pattern:
[<Workbook_name>]<Sheetname>!<Cell>
Example:
[MyWorkbook]Table1!A1
In HTML5, you can use CSS style.transform
.
However, i reccomend you "swipe between pages" turn off If you implement on Mac.
let l = 0;_x000D_
let t = 0;_x000D_
_x000D_
const MouseWheelHandler = (e) => {_x000D_
// vertical scroll_x000D_
if (e.deltaX == -0) {_x000D_
// t = t - e.deltaY_x000D_
_x000D_
// horizonal scroll_x000D_
} else if (e.deltaY == -0) {_x000D_
l = l - e.deltaX_x000D_
if (l >= 0) {_x000D_
l = 0;_x000D_
document.getElementById("gantt_task").style.transform = "translateX(1px)"_x000D_
document.getElementById("gantt_task_header").style.transform = "translateX(1px)"_x000D_
return false_x000D_
} _x000D_
document.getElementById("gantt_task").style.transform = "translateX(" + l.toString() + "px)"_x000D_
document.getElementById("gantt_task_header").style.transform = "translateX(" + l.toString() + "px)"_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
window.addEventListener("wheel", MouseWheelHandler, false);
_x000D_
.row {_x000D_
border-bottom: 1px solid #979A9A_x000D_
}_x000D_
#gantt_grid_header {_x000D_
height: 30px;_x000D_
width: 100px;_x000D_
position: fixed;_x000D_
z-index: 3;_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
border: 1px solid #cecece;_x000D_
background-color: #F08080;_x000D_
} _x000D_
_x000D_
#gantt_task_header {_x000D_
height: 30px;_x000D_
width: 400px;_x000D_
position: fixed;_x000D_
z-index: 2;_x000D_
top: 0px;_x000D_
left: 100px;_x000D_
border: 1px solid #cecece;_x000D_
background-color: #FFC300;_x000D_
}_x000D_
_x000D_
#gantt_grid {_x000D_
width: 100px; _x000D_
height: 400px;_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
z-index: 1;_x000D_
border: 1px solid #cecece;_x000D_
background-color: #DAF7A6;_x000D_
}_x000D_
_x000D_
#gantt_task {_x000D_
width: 400px; _x000D_
height: 400px;_x000D_
position: absolute;_x000D_
left: 100px;_x000D_
top: 0px;_x000D_
border: 1px solid #cecece;_x000D_
background-color: #FF5733;_x000D_
}
_x000D_
<html>_x000D_
<div id="gantt_grid_header">_x000D_
HEADER_x000D_
</div>_x000D_
<div id="gantt_grid">_x000D_
<div class="row">V Scroll OK</div>_x000D_
<div class="row">V Scroll OK</div>_x000D_
<div class="row">V Scroll OK</div>_x000D_
<div class="row">V Scroll OK</div>_x000D_
<div class="row">V Scroll OK</div>_x000D_
<div class="row">V Scroll OK</div>_x000D_
<div class="row">V Scroll OK</div>_x000D_
<div class="row">V Scroll OK</div>_x000D_
<div class="row">V Scroll OK</div>_x000D_
</div>_x000D_
<div id="gantt_task_header">_x000D_
DATA HEADER_x000D_
</div>_x000D_
<div id="gantt_task">_x000D_
<div class="row">Vertical,Horizenal Scroll OK</div>_x000D_
<div class="row">Vertical,Horizenal Scroll OK</div>_x000D_
<div class="row">Vertical,Horizenal Scroll OK</div>_x000D_
<div class="row">Vertical,Horizenal Scroll OK</div>_x000D_
<div class="row">Vertical,Horizenal Scroll OK</div>_x000D_
<div class="row">Vertical,Horizenal Scroll OK</div>_x000D_
<div class="row">Vertical,Horizenal Scroll OK</div>_x000D_
<div class="row">Vertical,Horizenal Scroll OK</div>_x000D_
<div class="row">Vertical,Horizenal Scroll OK</div>_x000D_
</div>_x000D_
</html>
_x000D_
To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)
For example this escapes the % symbol, using \ as the escape char:
select * from table where myfield like '%15\% off%' ESCAPE '\'
If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:
set @myString = replace(
replace(
replace(
replace( @myString
, '\', '\\' )
, '%', '\%' )
, '_', '\_' )
, '[', '\[' )
(Note that you have to escape your escape char too, and make sure that's the inner replace
so you don't escape the ones added from the other replace
statements). Then you can use something like this:
select * from table where myfield like '%' + @myString + '%' ESCAPE '\'
Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.
After jQuery 1.6, using promise seems like a better option.
var $div1 = $('#div1');
var fadeOutDone = $div1.fadeOut().promise();
// do your logic here, e.g.fetch your 2nd image url
$.get('secondimageinfo.json').done(function(data){
fadeoOutDone.then(function(){
$div1.html('<img src="' + data.secondImgUrl + '" alt="'data.secondImgAlt'">');
$div1.fadeIn();
});
});
Given it's SQL 2005, you can also try this It's similar to Oracle's MINUS command (opposite of UNION)
But I would also suggest adding the DATEPART ( hour, insertDate) column for debug
SELECT idCustomer FROM reservations
EXCEPT
SELECT idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2
I've had the problem which was two pronged:
1. In a form with multiple select2 elements, the dropdown won't open on tab, and you need to press space key to open it
2. Once you have made a selection, the tabindex won't be honored and you have to manually click on the next input field
While the usual suggestions worked, I came up with my own version, since a library script was doing the conversion of normal select to select2, and hence I had no control over this initialization.
Here is the code that worked for me.
Tab to open
$(document).on("focus", ".select2", function() {
$(this).siblings("select").select2("open");
});
Move to next on selection
var inputs = $("input,select"); // You can use other elements such as textarea, button etc.
//depending on input field types you have used
$("select").on("select2:close",function(){
var pos = $(inputs).index(this) + 1;
var next = $(inputs).eq(pos);
setTimeout( function() {
next.focus();
if (next.siblings(".select2").length) { //If it's a select
next.select2("open");
}
}, 500); //The delay is required to allow default events to occur
});
Hope this helps.
<span>
<img id="my_image" src="#" />
</span>
<span class="spanloader">
<span>set Loading Image Image</span>
</span>
<input type="button" id="btnnext" value="Next" />
<script type="text/javascript">
$('#btnnext').click(function () {
$(".spanloader").hide();
$("#my_image").attr("src", "1.jpg");
});
</script>
python setup.py install
is used to install (typically third party) packages that you're not going to develop/modify/debug yourself.
For your own stuff, you want to first install your package and then be able to frequently edit the code without having to re-install the package every time — and that is exactly what python setup.py develop
does: it installs the package (typically just a source folder) in a way that allows you to conveniently edit your code after it’s installed to the (virtual) environment, and have the changes take effect immediately.
Note that it is highly recommended to use pip install .
(install) and pip install -e .
(developer install) to install packages, as invoking setup.py
directly will do the wrong things for many dependencies, such as pull prereleases and incompatible package versions, or make the package hard to uninstall with pip
.
As the docs say, this can be achieved just by using set
instead if push
.
As the docs say, it is not recommended (due to possible overwrite by other user at the "same" time).
But in some cases it's helpful to have control over the feed's content including keys.
As an example of webapp in js, 193 being your id generated elsewhere, simply:
firebase.initializeApp(firebaseConfig);
var data={
"name":"Prague"
};
firebase.database().ref().child('areas').child("193").set(data);
This will overwrite any area labeled 193 or create one if it's not existing yet.
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width_px = Resources.getSystem().getDisplayMetrics().widthPixels;
int height_px =Resources.getSystem().getDisplayMetrics().heightPixels;
int pixeldpi = Resources.getSystem().getDisplayMetrics().densityDpi;
int width_dp = (width_px/pixeldpi)*160;
int height_dp = (height_px/pixeldpi)*160;
ES6+ version for 2021; no 1MB limit either:
This is adapted from @maia's version, updated for modern Javascript with the deprecated initMouseEvent replaced by new MouseEvent()
and the code generally improved:
const saveTemplateAsFile = (filename, jsonToWrite) => {
const blob = new Blob([jsonToWrite], { type: "text/json" });
const link = document.createElement("a");
link.download = filename;
link.href = window.URL.createObjectURL(blob);
link.dataset.downloadurl = ["text/json", link.download, link.href].join(":");
const evt = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
});
link.dispatchEvent(evt);
};
If you want to pass an object in:
const myObj = {};
const myObjAsJson = JSON.stringify(myObj);
saveTemplateAsFile(myObjAsJson);
You may well want to use JSON-P instead (see below). First a quick explanation.
The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest
) rather than the standard XMLHttpRequest
that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com
).
To get the JSON data you're requesting, you basically have three options:
If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)
Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax
call (just set dataType
to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:
{"weather": "Dreary start but soon brightening into a fine summer day."}
Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:
jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
That's it. JSON-P is very broadly compatible (because it works via JavaScript script
tags). JSON-P is only for GET
, though, not POST
(again because it works via script
tags).
Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:
A. The browser will send your server a "preflight" message using the OPTIONS
HTTP verb (method). It will contain the various headers it would send with the GET
or POST
as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET
or POST
), and "Access-Control-Request-Headers" (the headers it wants to send).
B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.
C. The browser will look at your response and see whether it's allowed to send you the actual GET
or POST
. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.
D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.
In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):
// Find out what the request is asking for
corsOrigin = get_request_header("Origin")
corsMethod = get_request_header("Access-Control-Request-Method")
corsHeaders = get_request_header("Access-Control-Request-Headers")
if corsOrigin is null or "null" {
// Requests from a `file://` path seem to come through without an
// origin or with "null" (literally) as the origin.
// In my case, for testing, I wanted to allow those and so I output
// "*", but you may want to go another way.
corsOrigin = "*"
}
// Decide whether to accept that request with those headers
// If so:
// Respond with headers saying what's allowed (here we're just echoing what they
// asked for, except we may be using "*" [all] instead of the actual origin for
// the "Access-Control-Allow-Origin" one)
set_response_header("Access-Control-Allow-Origin", corsOrigin)
set_response_header("Access-Control-Allow-Methods", corsMethod)
set_response_header("Access-Control-Allow-Headers", corsHeaders)
if the HTTP request method is "OPTIONS" {
// Done, no body in response to OPTIONS
stop
}
// Process the GET or POST here; output the body of the response
Again stressing that this is pseudo-code.
I think using this will be the easiest
new Uri("pack://application:,,/FolderIcon/" + youImageICO);
or this code will work on any machine that if your folder is in your root project if you want to change it... just change this section @"..\"
public static string bingPathToAppDir(string localPath)
{
string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(
Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + localPath)));
return directory.ToString();
}
The problem is that even JavaScript does not see the option
element being hovered. This is just to put emphasis on how it's not going to be solved (any time soon at least) by using just CSS:
window.onmouseover = function(e)
{
console.log(e.target.nodeName);
}
The only way to resolve this issue (besides waiting a millennia for browser vendors to fix bugs, let alone one that afflicts what you're trying to do) is to replace the drop-down menu with your own HTML/XML using JavaScript. This would likely involve the use of replacing the select
element with a ul
element and the use of a radio
input
element per li
element.
The jersey-container-servlet
actually uses the jersey-container-servlet-core
dependency. But if you use maven, that does not really matter. If you just define the jersey-container-servlet
usage, it will automatically download the dependency as well.
But for those who add jar files to their project manually (i.e. without maven) It is important to know that you actually need both jar files. The org.glassfish.jersey.servlet.ServletContainer
class is actually part of the core dependency.
If you have XDocument it is easier to use LINQ-to-XML:
var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;
If you are sure that XPath is the only solution you need:
using System.Xml.XPath;
var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;
select sequence_owner, sequence_name from dba_sequences;
DBA_SEQUENCES -- all sequences that exist
ALL_SEQUENCES -- all sequences that you have permission to see
USER_SEQUENCES -- all sequences that you own
Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES
, there is no SEQUENCE_OWNER
column in USER_SEQUENCES
.
Using Math.round()
will round the float to the nearest integer.
When using the Windows Subsystem for Linux (e.g. Ubuntu/Debian on WSL) the xclip
solution won't work. Instead you need to use clip.exe
and powershell.exe
to copy into and paste from the Windows clipboard.
This solution works on "real" Linux-based systems (i.e. Ubuntu, Debian) as well as on WSL systems. Just put the following code into your .bashrc
:
if grep -q -i microsoft /proc/version; then
# on WSL
alias copy="clip.exe"
alias paste="powershell.exe Get-Clipboard"
else
# on "normal" linux
alias copy="xclip -sel clip"
alias paste="xclip -sel clip -o"
fi
How it works
The file /proc/version
contains information about the currently running OS. When the system is running in WSL mode, then this file additionally contains the string Microsoft
which is checked by grep
.
To copy:
cat file | copy
And to paste:
paste > new_file
function isValue(value, def, is_return) {
if ( $.type(value) == 'null'
|| $.type(value) == 'undefined'
|| $.trim(value) == ''
|| ($.type(value) == 'number' && !$.isNumeric(value))
|| ($.type(value) == 'array' && value.length == 0)
|| ($.type(value) == 'object' && $.isEmptyObject(value)) ) {
return ($.type(def) != 'undefined') ? def : false;
} else {
return ($.type(is_return) == 'boolean' && is_return === true ? value : true);
}
}
try this~ all type checker
I ended up creating new Provisioning profiles, not sure if it was because of:
"The ad hoc distribution provisioning profile is corrupted and the device is having an issue with it."
I just wrote array intersection that correctly handles also duplicates
https://gist.github.com/gkucmierz/8ee04544fa842411f7553ef66ac2fcf0
// array intersection that correctly handles also duplicates_x000D_
_x000D_
const intersection = (a1, a2) => {_x000D_
const cnt = new Map();_x000D_
a2.map(el => cnt[el] = el in cnt ? cnt[el] + 1 : 1);_x000D_
return a1.filter(el => el in cnt && 0 < cnt[el]--);_x000D_
};_x000D_
_x000D_
const l = console.log;_x000D_
l(intersection('1234'.split``, '3456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('12344'.split``, '3456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('1234'.split``, '33456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('12334'.split``, '33456'.split``)); // [ '3', '3', '4' ]
_x000D_
It might be not totally related, but since the question mentioned react uses case (and I keep bumping into this SO thread): There is one important aspect of the double arrow function which is not explicitly mentioned here. Only the 'first' arrow(function) gets named (and thus 'distinguishable' by the run-time), any following arrows are anonymous and from React point of view count as a 'new' object on every render.
Thus double arrow function will cause any PureComponent to rerender all the time.
Example
You have a parent component with a change handler as:
handleChange = task => event => { ... operations which uses both task and event... };
and with a render like:
{
tasks.map(task => <MyTask handleChange={this.handleChange(task)}/>
}
handleChange then used on an input or click. And this all works and looks very nice. BUT it means that any change that will cause the parent to rerender (like a completely unrelated state change) will also re-render ALL of your MyTask as well even though they are PureComponents.
This can be alleviated many ways such as passing the 'outmost' arrow and the object you would feed it with or writing a custom shouldUpdate function or going back to basics such as writing named functions (and binding the this manually...)
For bitbucket repository, generate App Password (Bitbucket settings -> Access Management -> App Password, see the image) with read access to the repo and project.
Then the command that you should use is:
git clone https://username:[email protected]/reponame/projectname.git
You'd better use CSS for this:
td{
background-color:black;
color:white;
}
td:hover{
background-color:white;
color:black;
}
If you want to use these styles for only a specific set of elements, you should give your td
a class (or an ID, if it's the only element which'll have that style).
Example :
<td class="whiteHover"></td>
.whiteHover{
/* Same style as above */
}
Here's a reference on MDN for :hover
pseudo class.
A workaround to consider in a pinch:
The data in the database will have the quotes once the import is done... you can update the data later on to remove the quotes, or use the "replace" function in your read query, such as "replace([dbo].[MyTable].[MyColumn], '''', '')"
This is what I did to extract the piece of the directory:
for path in file_list:
directories = path.rsplit('\\')
directories.reverse()
line_replace_add_directory = line_replace+directories[2]
Thank you for your help.
Static memory allocation. Memory allocated will be in stack.
int a[10];
Dynamic memory allocation. Memory allocated will be in heap.
int *a = malloc(sizeof(int) * 10);
and the latter should be freed since there is no Garbage Collector(GC) in C.
free(a);
I will put here some real case examples and scenarios when to use one or another, it might be of help for somebody else:
HashMap
When you have to use cache in your application. Redis and membase are some type of extended HashMap. (Doesn't matter the order of the elements, you need quick ( O(1) ) read access (a value), using a key).
LinkedList
When the order is important (they are ordered as they were added to the LinkedList), the number of elements are unknown (don't waste memory allocation) and you require quick insertion time ( O(1) ). A list of to-do items that can be listed sequentially as they are added is a good example.
I got blur working with SVG blur filter:
CSS
-webkit-filter: url(#svg-blur);
filter: url(#svg-blur);
SVG
<svg id="svg-filter">
<filter id="svg-blur">
<feGaussianBlur in="SourceGraphic" stdDeviation="4"></feGaussianBlur>
</filter>
</svg>
Working example:
https://jsfiddle.net/1k5x6dgm/
Please note - this will not work in IE versions
Just to add a very simple solution, that was good enough for me, and I think addresses the OP's issue. I used the solution in this answer except with a regular Background
value instead of an image.
<Style x:Key="SomeButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
No re-templating beyond forcing the Background
to always be the Transparent
background from the templated button - mouseover no longer affects the background once this is done. Obviously replace Transparent
with any preferred value.
String.compareTo
might or might not be what you need.
Take a look at this link if you need localized ordering of strings.
I have tuned up previous code a little bit. First of all range.Changed hasn't work for me. After I changed range.Changed to richTextBox.TextChanged it turns out that TextChanged event handler can invoke SetDocumentXaml recursively, so I've provided protection against it. I also used XamlReader/XamlWriter instead of TextRange.
public class RichTextBoxHelper : DependencyObject
{
private static HashSet<Thread> _recursionProtection = new HashSet<Thread>();
public static string GetDocumentXaml(DependencyObject obj)
{
return (string)obj.GetValue(DocumentXamlProperty);
}
public static void SetDocumentXaml(DependencyObject obj, string value)
{
_recursionProtection.Add(Thread.CurrentThread);
obj.SetValue(DocumentXamlProperty, value);
_recursionProtection.Remove(Thread.CurrentThread);
}
public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(
"DocumentXaml",
typeof(string),
typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata(
"",
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
(obj, e) => {
if (_recursionProtection.Contains(Thread.CurrentThread))
return;
var richTextBox = (RichTextBox)obj;
// Parse the XAML to a document (or use XamlReader.Parse())
try
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(GetDocumentXaml(richTextBox)));
var doc = (FlowDocument)XamlReader.Load(stream);
// Set the document
richTextBox.Document = doc;
}
catch (Exception)
{
richTextBox.Document = new FlowDocument();
}
// When the document changes update the source
richTextBox.TextChanged += (obj2, e2) =>
{
RichTextBox richTextBox2 = obj2 as RichTextBox;
if (richTextBox2 != null)
{
SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));
}
};
}
)
);
}
I would not typecast away the const in the last line since it is there for a reason. If you can't live with a const char* then you better copy the char array like:
char* char_type = new char[temp_str.length()];
strcpy(char_type, temp_str.c_str());
var result = (35.8 / 100) * 10000;
(Thank you jball for this change of order of operations. I didn't consider it).
Question already answered by the OP, but I am posting this answer for anyone having similar problem, retting to
Could not input open file: composer.phar
error message.
Simply go to your project directory/folder and do a
composer update
Assuming this is where you have your web application:
/Library/WebServer/Documents/zendframework
change directory to it, and then run composer update
.
Further to pensz answer you can get more info using:
DESCRIBE EXTENDED my_table;
or
DESCRIBE EXTENDED my_table PARTITION (my_column='my_value');
This may happen if there is any read and write permission denial to the user. Like C:\Windows\System32\ have restricted access and you are cloned and trying to make from such restricted directory.
send a GET
to a page and the content replied will be the answer.Base url : http://website/api/
Have a look at json_encode() in PHP. You can get $.ajax to recognize this with the dataType: "json" parameter.
specifying the "antMatcher" before "authorizeRequests()" like below will restrict the authenticaiton to only those URLs specified in "antMatcher"
http.csrf().disable() .antMatcher("/apiurlneedsauth/**").authorizeRequests().
$('form :input').change(function() {
// Something has changed
});
Unfortunately it is not possible to do it.
jsPDF does not support exporting images and tables in fromHTML method. in jsPDF v0.9.0 rc2
I know this is three years old, but thought it might be helpful to someone.
The concept is to use the :after (or :before) selector to position a border within the parent element.
.container{
position:relative; /*Position must be set to something*/
}
.container:after{
position:relative;
top: 0;
content:"";
left:0;
height: 100%; /*Set pixel height and width if not defined in parent element*/
width: 100%;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
-ms-box-sizing:border-box;
box-sizing:border-box;
border:1px solid #000; /*set your border style*/
}
I solved my issue by removing this code from .csproj
file:
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
Using the example from Sarfraz above.
<div class="res">
<a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
~/Resumes/Resumes1271354404687.docx
</a>
</div>
$(function(){
$('.res').on('click', '.info_link', function(){
alert($(this)[0].href);
});
});
Gosha Arinich is right, you should return your <li>
element.
But, nevertheless, you should get nasty red warning in the browser console in this case
Each child in an array or iterator should have a unique "key" prop.
so, you need to add "key" to your list:
this.state.data.map(function(item, i){
console.log('test');
return <li key={i}>Test</li>
})
or drop the console.log()
and do a beautiful oneliner, using es6 arrow functions:
this.state.data.map((item,i) => <li key={i}>Test</li>)
IMPORTANT UPDATE:
The answer above is solving the current problem, but as Sergey mentioned in the comments: using the key depending on the map index is BAD if you want to do some filtering and sorting. In that case use the item.id
if id
already there, or just generate unique ids for it.
you have to iterate gridview Rows
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
{
((Label)grd.Rows[count].FindControl("labelID")).Text
}
}
This is your homework, so I assume you NEED to use the loops and switch statments. That's O.K, but why are all your loops inner to the privious ones ?
Just take them out to the same "level" and your code is just fine! (part to the low/up mixup).
A tip: Pressing extra 'Enter' & 'Space' is free! (That's the first thing I did to your code, and the problem became very trivial)
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
Before you run the $object through a foreach loop you have to convert it to an array:
$array = (array) $object;
foreach($array as $key=>$val){
echo "$key: $val";
echo "<br>";
}
Try this:
package my_default;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) {
try {
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook();
// Get first/desired sheet from the workbook
XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);
// XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
// because you get Sheet index (1) is out of range (no sheets)
//Write some information in the cells or do what you want
XSSFRow row1 = sheet.createRow(0);
XSSFCell r1c2 = row1.createCell(0);
r1c2.setCellValue("NAME");
XSSFCell r1c3 = row1.createCell(1);
r1c3.setCellValue("AGE");
//Save excel to HDD Drive
File pathToFile = new File("D:\\test.xlsx");
if (!pathToFile.exists()) {
pathToFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(pathToFile);
workbook.write(fos);
fos.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
XSSFSheet sheet = null;
int count = 0;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
String sName = wb.getSheetName(i);
if (sName.startsWith(prefix))
count++;
}
if (count > 0) {
sheet = wb.createSheet(prefix + count);
} else
sheet = wb.createSheet(prefix);
if (isHidden)
wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);
return sheet;
}
}
Add these to your /etc/ssh/ssh_config
Host *
UserKnownHostsFile=/dev/null
StrictHostKeyChecking=no
You also need to check Action_Down or Action_UP event. If you will not check then onKey() Method will call 2 times.
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Toast.makeText(getActivity(), "Back Pressed", Toast.LENGTH_SHORT).show();
return true;
}
}
return false;
}
});
Working very well for me.
I get the same error after i made changes with my data context. But i encounter something i am unfamiliar with. I get used to publish my files manually. Normally when i do that there is no App_Code folder appears in publishing folder. Bu i started to use VS 12 publishing which directly publishes with your assistance to the web server. And then i get the error about being precompiled application. Then i delete app_code folder it worked. But then it gave me the Data Context error that you are getting. So i just deleted all the files and run the publish again with no file restrictions (every folder & file will be published) then it worked like a charm.
This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().
http://louisremi.github.io/jquery.transform.js/
For example
$('#div').css({ transform: 'scale(.5)' });
OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.
http://www.browsersupport.net/CSS/zoom
Or just look at this question, which this one is likely just a dupe of:
43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back. http://en.wikipedia.org/wiki/ASCII
If you are not using any javascript/jquery for form validation, then a simple layout for your form would look like this.
within the body of your html document:
<form action="formHandler.php" name="yourForm" id="theForm" method="post">
<input type="text" name="fname" id="fname" />
<input type="submit" value="submit"/>
</form>
You need to ensure you have the submit button within the form tags, and an appropriate action assigned. Such as sending to a php file.
For a more direct answer, provide the code you are working with.
You may find the following of use: http://www.w3.org/TR/html401/interact/forms.html
To stop apache process try this command
ps aux | grep tomcat | awk '{print $2}' | xargs kill -9
There are different ways to do this, but the server can't detect when de browser gets closed so destroying it then is hard.
Either create a new session with the current time or add a time variable to the current session. and then check it when you start up or perform an action to see if the session has to be removed.
session_start();
$_SESSION["timeout"] = time();
//if 100 seconds have passed since creating session delete it.
if(time() - $_SESSION["timeout"] > 100){
unset($_SESSION["timeout"];
}
Make javascript perform an ajax call that will delete the session, with onbeforeunload()
a javascript function that calls a final action when the user leaves the page. For some reason this doesnt always work though.
If you always want the user to see the login page on startup after the page has been closed you can just delete the session on startup.
<? php
session_start();
unset($_SESSION["session"]);
and there probably are some more.
Following may be one more alternate solution to concatenate multiple strings.
String str1 = "sometext";
string str2 = "some other text";
string afterConcate = $"{str1}{str2}";
Here is an easy solution:
public class CapitalFirstLetters {
public static void main(String[] args) {
String word = "it's java, baby!";
String[] wordSplit;
String wordCapital = "";
wordSplit = word.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
wordCapital = wordSplit[i].substring(0, 1).toUpperCase() + wordSplit[i].substring(1) + " ";
}
System.out.println(wordCapital);
}}
Many of the List implementation support limited support to add/remove, and Arrays.asList(membersArray) is one of that. You need to insert the record in java.util.ArrayList or use the below approach to convert into ArrayList.
With the minimal change in your code, you can do below to convert a list to ArrayList. The first solution is having a minimum change in your solution, but the second one is more optimized, I guess.
String[] membersArray = request.getParameterValues('members');
ArrayList<String> membersList = new ArrayList<>(Arrays.asList(membersArray));
OR
String[] membersArray = request.getParameterValues('members');
ArrayList<String> membersList = Stream.of(membersArray).collect(Collectors.toCollection(ArrayList::new));
the cross browser code is:
$(window).scrollTop(300);
it is without animation but works everywhere
You need to use the option -f
:
$ grep -f A B
The option -F
does a fixed string search where as -f
is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.
$ grep -Ff A B
You may also want the -w
option for matching whole words only:
$ grep -wFf A B
Read man grep
for a description of all the possible arguments and what they do.
Dispatching and action inside of reducer seems occurs bug.
I made a simple counter example using useReducer
which "INCREASE" is dispatched then "SUB" also does.
In the example I expected "INCREASE" is dispatched then also "SUB" does and, set cnt
to -1 and then
continue "INCREASE" action to set cnt
to 0, but it was -1 ("INCREASE" was ignored)
See this: https://codesandbox.io/s/simple-react-context-example-forked-p7po7?file=/src/index.js:144-154
let listener = () => {
console.log("test");
};
const middleware = (action) => {
console.log(action);
if (action.type === "INCREASE") {
listener();
}
};
const counterReducer = (state, action) => {
middleware(action);
switch (action.type) {
case "INCREASE":
return {
...state,
cnt: state.cnt + action.payload
};
case "SUB":
return {
...state,
cnt: state.cnt - action.payload
};
default:
return state;
}
};
const Test = () => {
const { cnt, increase, substract } = useContext(CounterContext);
useEffect(() => {
listener = substract;
});
return (
<button
onClick={() => {
increase();
}}
>
{cnt}
</button>
);
};
{type: "INCREASE", payload: 1}
{type: "SUB", payload: 1}
// expected: cnt: 0
// cnt = -1
Generally speaking, you'll hardly ever need to do type comparisons unless you're doing something with reflection or interfaces. Nonetheless:
If you know the type you want to compare it with, use the is
or as
operators:
if( unknownObject is TypeIKnow ) { // run code here
The as
operator performs a cast that returns null if it fails rather than an exception:
TypeIKnow typed = unknownObject as TypeIKnow;
If you don't know the type and just want runtime type information, use the .GetType() method:
Type typeInformation = unknownObject.GetType();
In newer versions of C#, you can use the is
operator to declare a variable without needing to use as
:
if( unknownObject is TypeIKnow knownObject ) {
knownObject.SomeMember();
}
Previously you would have to do this:
TypeIKnow knownObject;
if( (knownObject = unknownObject as TypeIKnow) != null ) {
knownObject.SomeMember();
}
I've developed a nice JS solution - which is suitable for entirely-responsive HTML (i.e. HTML built with percentages)
I use only "em" to define font-sizes.
html font size is set to 10 pixels:
html {
font-size: 100%;
font-size: 62.5%;
}
I call a font-resizing function on document-ready:
// this requires JQuery
function doResize() {
// FONT SIZE
var ww = $('body').width();
var maxW = [your design max-width here];
ww = Math.min(ww, maxW);
var fw = ww*(10/maxW);
var fpc = fw*100/16;
var fpc = Math.round(fpc*100)/100;
$('html').css('font-size',fpc+'%');
}
Telerik Fiddler is a good choice
http://www.telerik.com/blogs/using-fiddler-with-apple-ios-devices
Let's say you have a cell with a subview, and you want the cell's height to be high enough to encompass the subview + padding.
1) Set the subview's bottom constraint equal to the cell.contentView minus the padding you want. Do not set constraints on the cell or cell.contentView itself.
2) Set either the tableView's rowHeight
property or tableView:heightForRowAtIndexPath:
to UITableViewAutomaticDimension
.
3) Set either the tableView's estimatedRowHeight
property or tableView:estimatedHeightForRowAtIndexPath:
to a best guess of the height.
That's it.
I had some trouble with $scope.$watch
but after a lot of testing I found out that my data-ng-model="User.UserName"
was badly named and after I changed it to data-ng-model="UserName"
everything worked fine. I expect it to be the .
in the name causing the issue.
C# in .NET 3.5 using System.DirectoryServices.AccountManagement.
bool valid = false;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
valid = context.ValidateCredentials( username, password );
}
This will validate against the current domain. Check out the parameterized PrincipalContext constructor for other options.
You should use Merge: For example:
MERGE INTO employees e
USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
or
MERGE INTO employees e
USING hr_records h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
DPLYR makes this really easy.
x<-santa%>%
count(Believe)
If you wanted to count by a group; for instance, how many males v females believe, just add a group_by
:
x<-santa%>%
group_by(Gender)%>%
count(Believe)
The best way is Mikael Eriksson, if ROW_NUMBER()
is available to you.
The next best is to join on a query, as per Cularis' answer.
Alternatively, the most simple and straight forward way is a correlated-sub-query in the WHERE clause.
SELECT
*
FROM
yourTable AS [data]
WHERE
DateEntered = (SELECT MAX(DateEntered) FROM yourTable WHERE orderNo = [data].orderNo)
Or...
WHERE
ID = (SELECT TOP 1 ID FROM yourTable WHERE orderNo = [data].orderNo ORDER BY DateEntered DESC)
You can add flex-direction:column
to flex-container
.flex-container {
flex-direction: column;
}
Add display:inline-block to flex-item
.flex-item {
display: inline-block;
}
because you added
width and height
has no effect on this element since it has a display ofinline
. Try addingdisplay:inline-block
ordisplay:block
. Learn more about width and height.
Also add to row class( you are given row{} not taken as style)
.row{
width:100%;
margin:0 auto;
text-align:center;
}
.flex-container {
padding: 0;
margin: 0;
list-style: none;
display: flex;
align-items: center;
justify-content:center;
flex-direction:column;
}
.row{
width:100%;
margin:0 auto;
text-align:center;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
display: inline-block;
}
_x000D_
<div class="flex-container">
<div class="row">
<span class="flex-item">1</span>
</div>
<div class="row">
<span class="flex-item">2</span>
</div>
<div class="row">
<span class="flex-item">3</span>
</div>
<div class="row">
<span class="flex-item">4</span>
</div>
</div>
_x000D_
.flex-container {
padding: 0;
margin: 0;
width: 100%;
list-style: none;
display: flex;
align-items: center;
}
.row {
width: 100%;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
display: inline-block;
}
_x000D_
<div class="flex-container">
<div class="row">
<span class="flex-item">1</span>
</div>
<div class="row">
<span class="flex-item">2</span>
</div>
<div class="row">
<span class="flex-item">3</span>
</div>
<div class="row">
<span class="flex-item">4</span>
</div>
</div>
_x000D_
So, is that a behavior to expect, a bug
Truth be told I am not sure. It looks like parser is interpreting count
not as a column name but a function and expects following parentheses. Looks like a bug or at least a serious limitation of the parser.
is there a canonical way to go around?
Some options have been already mentioned by Herman and mattinbits so here more SQLish approach from me:
import org.apache.spark.sql.functions.count
df.groupBy("x").agg(count("*").alias("cnt")).where($"cnt" > 2)
This is ES6 (with let declaration).
function checkExistingDate(year, month, day){ // year, month and day should be numbers
// months are intended from 1 to 12
let months31 = [1,3,5,7,8,10,12]; // months with 31 days
let months30 = [4,6,9,11]; // months with 30 days
let months28 = [2]; // the only month with 28 days (29 if year isLeap)
let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);
return valid; // it returns true or false
}
In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:
let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];
If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:
let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);
public static List<ApplicationInfo> getApplications(Context context) {
return context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
}
I would do the following,
JSONObject obj1 = /*json*/;
JSONObject obj2 = /*json*/;
ObjectMapper mapper = new ObjectMapper();
JsonNode tree1 = mapper.readTree(obj1.toString());
JsonNode tree2 = mapper.readTree(obj2.toString());
return tree1.equals(tree2);
Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.
https://jsfiddle.net/mvora/mrLmkxmo/
/******** PUT THIS CODE IN ONE JS FILE *******/
var secondFileFuntion = function(){
this.name = 'XYZ';
}
secondFileFuntion.prototype.getSurname = function(){
return 'ABC';
}
var secondFileObject = new secondFileFuntion();
/******** Till Here *******/
/******** PUT THIS CODE IN SECOND JS FILE *******/
function firstFileFunction(){
var name = secondFileObject.name;
var surname = secondFileObject.getSurname()
alert(name);
alert(surname );
}
firstFileFunction();
If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.
Just take care of sequence of including these files in index.html
I have been using splitmix64
(pointed in Thomas Mueller's answer) ever since I found this thread. However, I recently stumbled upon Pelle Evensen's rrxmrrxmsx_0, which yielded tremendously better statistical distribution than the original MurmurHash3 finalizer and its successors (splitmix64
and other mixes). Here is the code snippet in C:
#include <stdint.h>
static inline uint64_t ror64(uint64_t v, int r) {
return (v >> r) | (v << (64 - r));
}
uint64_t rrxmrrxmsx_0(uint64_t v) {
v ^= ror64(v, 25) ^ ror64(v, 50);
v *= 0xA24BAED4963EE407UL;
v ^= ror64(v, 24) ^ ror64(v, 49);
v *= 0x9FB21C651E98DF25UL;
return v ^ v >> 28;
}
Pelle also provides an in-depth analysis of the 64-bit mixer used in the final step of MurmurHash3
and the more recent variants.
substring(int startpos, int lenght);
The following illustrates the syntax of the STR_TO_DATE()
function:
STR_TO_DATE(str,fmt);
The STR_TO_DATE()
converts the str string into a date value based on the fmt format string. The STR_TO_DATE()
function may return a DATE , TIME, or DATETIME value based on the input and format strings. If the input string is illegal, the STR_TO_DATE()
function returns NULL.
The following statement converts a string into a DATE value.
SELECT STR_TO_DATE('21,5,2013','%d,%m,%Y');
Based on the format string ‘%d, %m, %Y’, the STR_TO_DATE()
function scans the ‘21,5,2013’ input string.
STR_TO_DATE()
function keeps finding a match for the third format specifier %Y ,
which is four-digit year e.g., 2012,2013, etc., and it takes the
number 2013 as the year value.The STR_TO_DATE()
function ignores extra characters at the end of the input string when it parses the input string based on the format string. See the following example:
SELECT STR_TO_DATE('21,5,2013 extra characters','%d,%m,%Y');
More Details : Reference
This is the proper way to access data in laravel :
@foreach($data-> ac as $link)
{{$link->url}}
@endforeach
Locate the following file
C:\Users\
[your name]\.android\adb_usb.ini
And make the following changes:
# ANDROID 3RD PARTY USB VENDOR ID LIST -- DO NOT EDIT.
# USE 'android update adb' TO GENERATE.
# 1 USB VENDOR ID PER LINE.
0x2207
I added 0x2207
to the file. This number is part of the hardware id, which can be found under the device's hardware information.
Mine was:
USB\VID_2207&PID_0010&MI_01
(I tried executing android update adb
, but it did nothing.)
Just yesterday I've added my git-analytics docker-compose file, which builds up several containers to start analyzing multiple git repositories against each other.
It is able to show you commit statistics over time about the author and also several diff statistics.
You can use the provided angular client and also kibana to visualize the statistics.
https://github.com/alexejsailer/git-analytics-docker
It will be improved over time.
Just to answer your question and not to continue any discussions. The Apache Harmony JDK implementation seems to use a different algorithm, at least it looks totally different:
Sun JDK
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
Apache Harmony
public int hashCode() {
if (hashCode == 0) {
int hash = 0, multiplier = 1;
for (int i = offset + count - 1; i >= offset; i--) {
hash += value[i] * multiplier;
int shifted = multiplier << 5;
multiplier = shifted - multiplier;
}
hashCode = hash;
}
return hashCode;
}
Feel free to check it yourself...
I was using pgAdmin to create my tables and while I was not using reserved words, the generated table had a quote in the name and a couple of columns had quotes in them. Here is an example of the generated SQL.
CREATE TABLE public."Test"
(
id serial NOT NULL,
data text NOT NULL,
updater character varying(50) NOT NULL,
"updateDt" time with time zone NOT NULL,
CONSTRAINT test_pk PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE public."Test"
OWNER to svc_newnews_app;
All of these quotes were inserted at "random". I just needed to drop and re-create the table again without the quotes.
Tested on pgAdmin 4.26
//To Find Max and Min value in an array without sorting in java
import java.util.Scanner;
import java.util.*;
public class MaxMin_WoutSort {
public static void main(String args[])
{
int n,max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;
System.out.println("Enter the number of elements: ");
Scanner sc = new Scanner(System.in);
int[] arr = new int[sc.nextInt()]; //U can't say static or dynamic.
//UnWrapping object sc to int value;sc.nextInt()
System.out.println("Enter the elements: ");
for(int i=0;i<arr.length;i++) //Loop for entering values in array
{
int next = sc.nextInt();
arr[i] = next;
}
for(int j=0;j<arr.length;j++)
{
if(arr[j]>max) //Maximum Condition
max = arr[j];
else if(arr[j]<min) //Minimum Condition
min = arr[j];
}
System.out.println("Highest Value in array: " +max);
System.out.println("Smallest Value in array: "+min);
}
}
They say it right there in the documentation for the FPDF constructor:
FPDF([string orientation [, string unit [, mixed size]]])
This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...
size
The size used for pages. It can be either one of the following values (case insensitive):
A3 A4 A5 Letter Legal
or an array containing the width and the height (expressed in the unit given by unit).
They even give an example with custom size:
Example with a custom 100x150 mm page size:
$pdf = new FPDF('P','mm',array(100,150));
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
Atom does not have block comment by default, so I would recommend searching for atom packages by "block comment" and install the one suits to you.
I prefer https://atom.io/packages/block-comment because is has the closest keyboard shortcut to line comment and it works as i need it to, meaning it would not comment the whole line but only the selected text.
line comment: CTRL+/
block comment: CTRL+SHIFT+/
(with the plugin installed)
You can use strpos()
or stripos()
to check if the string contain the given needle. It will return the position where it was found, otherwise will return FALSE.
Use the operators ===
or `!== to differ FALSE from 0 in PHP.
I want to put the correct answer in here, just in case others are having this problem like I was. If you hate the ViewBag, fine don't use it, but the real problem with the code in the question is that the same name is being used for both the model property and the selectlist as was pointed out by @RickAndMSFT
Simply changing the name of the DropDownList control should resolve the issue, like so:
@Html.DropDownList("NewsCategoriesSelection", (SelectList)ViewBag.NewsCategoriesID)
It doesn't really have anything to do with using the ViewBag or not using the ViewBag as you can have a name collision with the control regardless.
None of the above answers fixed this issue for me. I did it as following (Laravel with Ubuntu server):
<?php
$footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
include($footerFile);
?>
You would need also to import the HttpClientModule
from Angular '@angular/common/http'
into your main AppModule for making HTTP requests.
app.module.ts
import { HttpClientModule } from '@angular/common/http';
import { ServiceService } from '../../../services/service.service';
@NgModule({
imports: [
HttpClientModule
],
providers: [
ServiceService
]
})
export class AppModule {...}
I know you're claiming language-agnostic on this, but can you tell us what you're using just so we know what regex capabilities you have?
If you have the capabilities for non-capturing matches, you can modify hometoast's expression so that subexpressions that you aren't interested in capturing are set up like this:
(?:SOMESTUFF)
You'd still have to copy and paste (and slightly modify) the Regex into multiple places, but this makes sense--you're not just checking to see if the subexpression exists, but rather if it exists as part of a URL. Using the non-capturing modifier for subexpressions can give you what you need and nothing more, which, if I'm reading you correctly, is what you want.
Just as a small, small note, hometoast's expression doesn't need to put brackets around the 's' for 'https', since he only has one character in there. Quantifiers quantify the one character (or character class or subexpression) directly preceding them. So:
https?
would match 'http' or 'https' just fine.
ECMAScript 6 introduced arrow functions so now the setTimeout() or setInterval() don't have to look like this:
setTimeout(function() { FetchData(); }, 1000)
Instead, you can use annonymous arrow function which looks cleaner, and less confusing:
setTimeout(() => {FetchData();}, 1000)
select * into newtable from oldtable
Best guess:
var cur_value = $('#select-id').children('option:selected').text();
I like children better in this case because you know you're only going one branch down the DOM tree...
As an alternative you can also query the information_schema
database and retrieve the data from the global_variables
(and global_status
of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.
For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size
in bytes and megabytes:
SELECT
variable_name,
variable_value AS innodb_log_buffer_size_bytes,
ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE 'innodb_log_buffer_size';
As a result you get:
+------------------------+------------------------------+---------------------------+
| variable_name | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456 | 256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)
Since none of the suggestions above helped me with charts.js 2.1.4, I solved it by adding the value 0 to my data set array (but no extra label):
statsData.push(0);
[...]
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
datasets: [{
data: statsData,
[...]
Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:
var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) {
return v.value;
});
UPDATE (2017-02-14):
An even more succinct way using ES6/ES2015 (for the browsers that support it):
const selected = document.querySelectorAll('#select-meal-type option:checked');
const values = Array.from(selected).map(el => el.value);
Select ename, job, sal from emp
where sal >=(select max(sal) from emp
where sal < (select max(sal) from emp
where sal < (select max(sal) from emp)))
order by sal;
ENAME JOB SAL
---------- --------- ----------
KING PRESIDENT 5000
FORD ANALYST 3000
SCOTT ANALYST 3000
You could do this using my Common Node library:
function get(url) {
return new (require('httpclient').HttpClient)({
method: 'GET',
url: url
}).finish().body.read().decodeToString();
}
var a = get('www.example.com/api_1.php'),
b = get('www.example.com/api_2.php'),
c = get('www.example.com/api_3.php');
if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.
If it is a study project then keep at it and learn from your exploring :)
The way I'd do this is:
="'"&K2
Ctrl+D
to fill it down to the length of Column K's values.from django.http import HttpResponse
import json
class JsonResponse(HttpResponse):
def __init__(self, content={}, mimetype=None, status=None,
content_type='application/json'):
super(JsonResponse, self).__init__(json.dumps(content), mimetype=mimetype,
status=status, content_type=content_type)
And in the view:
resp_data = {'my_key': 'my value',}
return JsonResponse(resp_data)
I was using salesforce apex classes with Eclipse Neon 3.3 for Java.
I found an option "define folding region" on right click in the editor, I selected the block of code i wanted to collapse and selected this property for that code. Now I am seeing + and - symbol to expand and collapse that block of code
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
I tried all the mentioned things above but could not resolve the issue. I am using SQLite and my SQLite file was in the resources directory.
a) Set Up done for IDE
I need to manually add below lines in the .classpath file of my project.
<classpathentry kind="src" path="resources"/>
<classpathentry kind="output" path="target/classes"/>
After that, I refreshed and Cleaned the project from MenuBar at the top. like Project->Clean->My Project Name.
After that, I run the project and problem resolved.
application.properties for my project is
spring.datasource.url=jdbc:sqlite:resources/apiusers.sqlite
spring.datasource.driver-class-name=org.sqlite.JDBC
spring.jpa.properties.hibernate.dialect=com.enigmabridge.hibernate.dialect.SQLiteDialect
spring.datasource.username=
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
b) Set Up done if Jar deployment throw same error
You need to add following lines to your pom.xml
<build>
<resources>
<resource>
<directory>resources</directory>
<targetPath>${project.build.outputDirectory}</targetPath>
<includes>
<include>application.properties</include>
</includes>
</resource>
</resources>
</build>
May be it may help someone.
I'm not gonna claim that this is more elegant than the highest-voted solution...but this is cool (well, at least in my mind LOL) in its own way:
$server = "ftp.lolcats.com"
$filelist = "file1.txt file2.txt"
"open $server
user $user $password
binary
cd $dir
" +
($filelist.split(' ') | %{ "put ""$_""`n" }) | ftp -i -in
As you can see, it uses that dinky built-in windows FTP client. Much shorter and straightforward, too. Yes, I've actually used this and it works!
Godaddy hosting it seems fixed on .htaccess
, myself it is working
RewriteRule ^(.*)$ index.php/$1 [L]
to
RewriteRule ^(.*)$ index.php?/$1 [QSA,L]
Here is some stuff to download all buckets, list them, list their contents.
//connection string
private static void dBConnection() {
app.setAwsCredentials(CONST.getAccessKey(), CONST.getSecretKey());
conn = new AmazonS3Client(app.getAwsCredentials());
app.setListOfBuckets(conn.listBuckets());
System.out.println(CONST.getConnectionSuccessfullMessage());
}
private static void downloadBucket() {
do {
for (S3ObjectSummary objectSummary : app.getS3Object().getObjectSummaries()) {
app.setBucketKey(objectSummary.getKey());
app.setBucketName(objectSummary.getBucketName());
if(objectSummary.getKey().contains(CONST.getDesiredKey())){
//DOWNLOAD
try
{
s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
s3Client.getObject(
new GetObjectRequest(app.getBucketName(),app.getBucketKey()),
new File(app.getDownloadedBucket())
);
} catch (IOException e) {
e.printStackTrace();
}
do
{
if(app.getBackUpExist() == true){
System.out.println("Converting back up file");
app.setCurrentPacsId(objectSummary.getKey());
passIn = app.getDataBaseFile();
CONVERT= new DataConversion(passIn);
System.out.println(CONST.getFileDownloadedMessage());
}
}
while(app.getObjectExist()==true);
if(app.getObjectExist()== false)
{
app.setNoObjectFound(true);
}
}
}
app.setS3Object(conn.listNextBatchOfObjects(app.getS3Object()));
}
while (app.getS3Object().isTruncated());
}
/----------------------------Extension Methods-------------------------------------/
//Unzip bucket after download
public static void unzipBucket() throws IOException {
unzip = new UnZipBuckets();
unzip.unZipIt(app.getDownloadedBucket());
System.out.println(CONST.getFileUnzippedMessage());
}
//list all S3 buckets
public static void listAllBuckets(){
for (Bucket bucket : app.getListOfBuckets()) {
String bucketName = bucket.getName();
System.out.println(bucketName + "\t" + StringUtils.fromDate(bucket.getCreationDate()));
}
}
//Get the contents from the auto back up bucket
public static void listAllBucketContents(){
do {
for (S3ObjectSummary objectSummary : app.getS3Object().getObjectSummaries()) {
if(objectSummary.getKey().contains(CONST.getDesiredKey())){
System.out.println(objectSummary.getKey() + "\t" + objectSummary.getSize() + "\t" + StringUtils.fromDate(objectSummary.getLastModified()));
app.setBackUpCount(app.getBackUpCount() + 1);
}
}
app.setS3Object(conn.listNextBatchOfObjects(app.getS3Object()));
}
while (app.getS3Object().isTruncated());
System.out.println("There are a total of : " + app.getBackUpCount() + " buckets.");
}
}
I have encountered the very similar problem today. For some reason IntelliJ IDEA
haven't included Spring Security jar files while deploying the application. I think I should agree with the majority of posters here.
The selected answer doesn't work quite well with multiple sessions and doesn't allow to specify a custom log file name.
For multiple screen sessions, this is my formula:
Create a configuration file for each process:
logfile test.log
logfile flush 1
log on
logtstamp after 1
logtstamp string "[ %t: %Y-%m-%d %c:%s ]\012"
logtstamp on
If you want to do it "on the fly", you can change logfile
automatically.
\012
means "new line", as using \n
will print it on the log file: source.
Start your command with the "-c" and "-L" flags:
screen -c ./test.conf -dmSL 'Test' ./test.pl
That's it. You will see "test.log" after the first flush:
...
6 Something is happening...
[ test.pl: 2016-06-01 13:02:53 ]
7 Something else...
[ test.pl: 2016-06-01 13:02:54 ]
8 Nothing here
[ test.pl: 2016-06-01 13:02:55 ]
9 Something is happening...
[ test.pl: 2016-06-01 13:02:56 ]
10 Something else...
[ test.pl: 2016-06-01 13:02:57 ]
11 Nothing here
[ test.pl: 2016-06-01 13:02:58 ]
...
I found that "-L" is still required even when "log on" is on the configuration file.
I couldn't find a list of the time format variables (like %m) used by screen. If you have a link of those formats, please post it bellow.
In case you want to do it "on the fly", you can use this script:
#!/bin/bash
if [[ $2 == "" ]]; then
echo "Usage: $0 name command";
exit 1;
fi
name=$1
command=$2
path="/var/log";
config="logfile ${path}/${name}.log
logfile flush 1
log on
logtstamp after 1
logtstamp string \"[ %t: %Y-%m-%d %c:%s ]\012\"
logtstamp on";
echo "$config" > /tmp/log.conf
screen -c /tmp/log.conf -dmSL "$name" $command
rm /tmp/log.conf
To use it, save it (screen.sh) and set +x permissions:
./screen.sh TEST ./test.pl
... and will execute ./test.pl and create a log file in /var/log/TEST.log
Calling addView
is the correct answer, but you need to do a little more than that to get it to work.
If you create a View via a constructor (e.g., Button myButton = new Button();
), you'll need to call setLayoutParams
on the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.
For example, you might have the following code in your onCreate()
function assuming your LinearLayout has id R.id.main
:
LinearLayout myLayout = findViewById(R.id.main);
Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
myLayout.addView(myButton);
Making sure to set the LayoutParams is important. Every view needs at least a layout_width and a layout_height parameter. Also getting the right inner class is important. I struggled with getting Views added to a TableRow to display properly until I figured out that I wasn't passing an instance of TableRow.LayoutParams to the child view's setLayoutParams.
I found that with spring boot 2.0.2.RELEASE, configuring spring-boot-starter-data-jpa and com.h2database in the POM file is not just enough to have H2 console working. You must configure spring-boot-devtools as below. Optionally you could follow the instruction from Aaron Zeckoski in this post
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
Think this is, what you are searching for: Allow access to specific projects for Users
Short description without screenshots:
Use Jenkins "Project-based Matrix Authorization Strategy" under "Manage Jenkins" => "Configure System". On the configuration page of each project, you now have "Enable project-based security". Now add each user you want to authorize.
As selected answer says you can use findAndModify to generate sequential IDs.
But I strongly disagree with opinion that you should not do that. It all depends on your business needs. Having 12-byte ID may be very resource consuming and cause significant scalability issues in future.
I have detailed answer here.
This snippet successfully allows to reuse existing browser instance yet avoiding raising the duplicate browser. Found at Tarun Lalwani's blog.
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
# executor_url = driver.command_executor._url
# session_id = driver.session_id
def attach_to_session(executor_url, session_id):
original_execute = WebDriver.execute
def new_command_execute(self, command, params=None):
if command == "newSession":
# Mock the response
return {'success': 0, 'value': None, 'sessionId': session_id}
else:
return original_execute(self, command, params)
# Patch the function before creating the driver object
WebDriver.execute = new_command_execute
driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
driver.session_id = session_id
# Replace the patched function with original function
WebDriver.execute = original_execute
return driver
bro = attach_to_session('http://127.0.0.1:64092', '8de24f3bfbec01ba0d82a7946df1d1c3')
bro.get('http://ya.ru/')
No, that's not really possible, as
The goal of the MD5 and its family of hashing functions is
Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.
This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...
In python3 with virtualenv on a Ubuntu Bionic machine the following commands worked for me:
sudo apt install build-essential python-dev libmysqlclient-dev
sudo apt-get install libssl-dev
pip install mysqlclient
== ISSUE THIS COMMAND
[xxx@devxxx ~]$ screen -ls
== SCREEN RESPONDS
There are screens on:
23487.pts-0.devxxx (Detached)
26727.pts-0.devxxx (Attached)
2 Sockets in /tmp/uscreens/S-xxx.
== NOW KILL THE ONE YOU DONT WANT
[xxx@devxxx ~]$ screen -X -S 23487.pts-0.devxxx kill
== WANT PROOF?
[xxx@devxxx ~]$ screen -ls
There is a screen on:
26727.pts-0.devxxx (Attached)
1 Socket in /tmp/uscreens/S-xxx.
On Linux with Inkscape 1.0 to convert from svg to png need to use
inkscape -w 1024 -h 1024 input.svg --export-file output.png
not
inkscape -w 1024 -h 1024 input.svg --export-filename output.png
What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:
angular.module('myApp').directive('conversation', function() {
return {
restrict: 'E',
replace: true,
compile: function(tElement, attr) {
attr.$observe('typeId', function(data) {
console.log("Updated data ", data);
}, true);
}
};
});
Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.
If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:
<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>
And in the directive:
angular.module('myApp').directive('conversation', function() {
return {
scope: {
typeId: '=',
},
link: function(scope, elm, attr) {
scope.$watch('typeId', function(newValue, oldValue) {
if (newValue !== oldValue) {
// You actions here
console.log("I got the new value! ", newValue);
}
}, true);
}
};
});
Edit: my bad, you wanted the select to show results after the update, not update from a select.
Have you tried a sub-select?
update mytable set mydate = sysdate
where mydate in (select mydate from mytable where mydate is null);
If any of the above method is not working and you code is perfect then try hard refreshing by pressing Ctrl + F5. It will clear all the chaces and then reload file. It worked for me.
Although I have not tried this out, ProcDump seems like a better solution.
Description from site:
ProcDump is a command-line utility whose primary purpose is monitoring an application for CPU spikes and generating crash dumps during a spike that an administrator or developer can use to determine the cause of the spike. ProcDump also includes hung window monitoring (using the same definition of a window hang that Windows and Task Manager use), unhandled exception monitoring and can generate dumps based on the values of system performance counters. It also can serve as a general process dump utility that you can embed in other scripts.
I had the same problem here. In my case I need to use an old version of JDK and I'm using sdkmanager to manage the versions of JDK, so, I changed the version of the virtual machine to 1.8.
sdk use java 8.0.222.j9-adpt
After that, the app runs as expected here.
Use curly brackets and put all the attributes you want to add inside
Example:
$('#objId').attr({
target: 'nw',
title: 'Opens in a new window'
});
As an addition, you can also mix different ways of usage when calling kwargs functions:
def test(**kwargs):
print kwargs['a']
print kwargs['b']
print kwargs['c']
args = { 'b': 2, 'c': 3}
test( a=1, **args )
gives this output:
1
2
3
Note that **kwargs has to be the last argument
You could also, higlight the text you want to change, then navigate to - 'Edit' > 'Convert Case to' choose UPPERCASE or lowercase (as required).
My refactor of @Brian answer
var string = 'and this is some kind of information and another text and simple and some egample or red or text';_x000D_
var separators = ['and', 'or'];_x000D_
_x000D_
function splitMulti(str, separators){_x000D_
var tempChar = 't3mp'; //prevent short text separator in split down_x000D_
_x000D_
//split by regex e.g. \b(or|and)\b_x000D_
var re = new RegExp('\\b(' + separators.join('|') + ')\\b' , "g");_x000D_
str = str.replace(re, tempChar).split(tempChar);_x000D_
_x000D_
// trim & remove empty_x000D_
return str.map(el => el.trim()).filter(el => el.length > 0);_x000D_
}_x000D_
_x000D_
console.log(splitMulti(string, separators))
_x000D_
To extract joebloggs
from this string in bash using parameter expansion without any extra processes...
MYVAR="/var/cpanel/users/joebloggs:DNS9=domain.com"
NAME=${MYVAR%:*} # retain the part before the colon
NAME=${NAME##*/} # retain the part after the last slash
echo $NAME
Doesn't depend on joebloggs
being at a particular depth in the path.
Summary
An overview of a few parameter expansion modes, for reference...
${MYVAR#pattern} # delete shortest match of pattern from the beginning
${MYVAR##pattern} # delete longest match of pattern from the beginning
${MYVAR%pattern} # delete shortest match of pattern from the end
${MYVAR%%pattern} # delete longest match of pattern from the end
So #
means match from the beginning (think of a comment line) and %
means from the end. One instance means shortest and two instances means longest.
You can get substrings based on position using numbers:
${MYVAR:3} # Remove the first three chars (leaving 4..end)
${MYVAR::3} # Return the first three characters
${MYVAR:3:5} # The next five characters after removing the first 3 (chars 4-9)
You can also replace particular strings or patterns using:
${MYVAR/search/replace}
The pattern
is in the same format as file-name matching, so *
(any characters) is common, often followed by a particular symbol like /
or .
Examples:
Given a variable like
MYVAR="users/joebloggs/domain.com"
Remove the path leaving file name (all characters up to a slash):
echo ${MYVAR##*/}
domain.com
Remove the file name, leaving the path (delete shortest match after last /
):
echo ${MYVAR%/*}
users/joebloggs
Get just the file extension (remove all before last period):
echo ${MYVAR##*.}
com
NOTE: To do two operations, you can't combine them, but have to assign to an intermediate variable. So to get the file name without path or extension:
NAME=${MYVAR##*/} # remove part before last slash
echo ${NAME%.*} # from the new var remove the part after the last period
domain
Have a look at py-multicast. Network module can check if an interface supports multicast (on Linux at least).
import multicast
from multicast import network
receiver = multicast.MulticastUDPReceiver ("eth0", "238.0.0.1", 1234 )
data = receiver.read()
receiver.close()
config = network.ifconfig()
print config['eth0'].addresses
# ['10.0.0.1']
print config['eth0'].multicast
#True - eth0 supports multicast
print config['eth0'].up
#True - eth0 is up
Perhaps problems with not seeing IGMP, were caused by an interface not supporting multicast?
Destructing assignment is the best way to solve your problem.
var a = 1;
var b = 2;
[a, b] = [b, a];
console.log("After swap a =", a, " and b =", b);
_x000D_
Here is my solution
[^0-9A-Z,\n]
This will remove all the digits, commas and new lines but select the middle space such as data set of
In most browsers, there's a slightly more succinct way of removing an element from the DOM than calling .removeChild(element)
on its parent, which is to just call element.remove()
. In due course, this will probably become the standard and idiomatic way of removing an element from the DOM.
The .remove()
method was added to the DOM Living Standard in 2011 (commit), and has since been implemented by Chrome, Firefox, Safari, Opera, and Edge. It was not supported in any version of Internet Explorer.
If you want to support older browsers, you'll need to shim it. This turns out to be a little irritating, both because nobody seems to have made a all-purpose DOM shim that contains these methods, and because we're not just adding the method to a single prototype; it's a method of ChildNode
, which is just an interface defined by the spec and isn't accessible to JavaScript, so we can't add anything to its prototype. So we need to find all the prototypes that inherit from ChildNode
and are actually defined in the browser, and add .remove
to them.
Here's the shim I came up with, which I've confirmed works in IE 8.
(function () {
var typesToPatch = ['DocumentType', 'Element', 'CharacterData'],
remove = function () {
// The check here seems pointless, since we're not adding this
// method to the prototypes of any any elements that CAN be the
// root of the DOM. However, it's required by spec (see point 1 of
// https://dom.spec.whatwg.org/#dom-childnode-remove) and would
// theoretically make a difference if somebody .apply()ed this
// method to the DOM's root node, so let's roll with it.
if (this.parentNode != null) {
this.parentNode.removeChild(this);
}
};
for (var i=0; i<typesToPatch.length; i++) {
var type = typesToPatch[i];
if (window[type] && !window[type].prototype.remove) {
window[type].prototype.remove = remove;
}
}
})();
This won't work in IE 7 or lower, since extending DOM prototypes isn't possible before IE 8. I figure, though, that on the verge of 2015 most people needn't care about such things.
Once you've included them shim, you'll be able to remove a DOM element element
from the DOM by simply calling
element.remove();
Float each div and set clear;both for the row. No need to set widths if you dont want to. Works in Chrome 41,Firefox 37, IE 11
<div class="stack">
<div class="row">
<div class="col">
One
</div>
<div class="col">
Two
</div>
</div>
<div class="row">
<div class="col">
One
</div>
<div class="col">
Two
</div>
<div class="col">
Three
</div>
</div>
</div>
.stack .row {
clear:both;
}
.stack .row .col {
float:left;
border:1px solid;
}
First, check the location of anaconda, for me I installed anaconda3 at / directory which I access with /anaconda3
Then in your terminal, input export PATH="<base location>/anaconda3/bin:$PATH"
for me it's export PATH="/anaconda3/bin:$PATH"
.
Finally, input source $/anaconda3/bin/activate
. For you, just change to your location.
Now, you could try conda list to test.
Also, visit intallation guide
If you want to get unique elements from a list and keep their original order, then you may employ OrderedDict
data structure from Python's standard library:
from collections import OrderedDict
def keep_unique(elements):
return list(OrderedDict.fromkeys(elements).keys())
elements = [2, 1, 4, 2, 1, 1, 5, 3, 1, 1]
required_output = [2, 1, 4, 5, 3]
assert keep_unique(elements) == required_output
In fact, if you are using Python = 3.6, you can use plain dict
for that:
def keep_unique(elements):
return list(dict.fromkeys(elements).keys())
It's become possible after the introduction of "compact" representation of dicts. Check it out here. Though this "considered an implementation detail and should not be relied upon".
this one is pretty good and it also works in angular 2
$("#modal .close").click()
I was always confused about whether delegates should be weak or not. Recently I've learned more about delegates and when to use weak references, so let me add some supplemental points here for the sake of future viewers.
The purpose of using the weak
keyword is to avoid strong reference cycles (retain cycles). Strong reference cycles happen when two class instances have strong references to each other. Their reference counts never go to zero so they never get deallocated.
You only need to use weak
if the delegate is a class. Swift structs and enums are value types (their values are copied when a new instance is made), not reference types, so they don't make strong reference cycles.
weak
references are always optional (otherwise you would used unowned
) and always use var
(not let
) so that the optional can be set to nil
when it is deallocated.
A parent class should naturally have a strong reference to its child classes and thus not use the weak
keyword. When a child wants a reference to its parent, though, it should make it a weak reference by using the weak
keyword.
weak
should be used when you want a reference to a class that you don't own, not just for a child referencing its parent. When two non-hierarchical classes need to reference each other, choose one to be weak. The one you choose depends on the situation. See the answers to this question for more on this.
As a general rule, delegates should be marked as weak
because most delegates are referencing classes that they do not own. This is definitely true when a child is using a delegate to communicate with a parent. Using a weak reference for the delegate is what the documentation recommends. (But see this, too.)
Protocols can be used for both reference types (classes) and value types (structs, enums). So in the likely case that you need to make a delegate weak, you have to make it an object-only protocol. The way to do that is to add AnyObject
to the protocol's inheritance list. (In the past you did this using the class
keyword, but AnyObject
is preferred now.)
protocol MyClassDelegate: AnyObject {
// ...
}
class SomeClass {
weak var delegate: MyClassDelegate?
}
Reading the following articles is what helped me to understand this much better. They also discuss related issues like the unowned
keyword and the strong reference cycles that happen with closures.
In my case, on top of adding google() in repositories for the project level gradle file, I had to also include it in the app level gradle file.
repositories {
mavenLocal()
google()
flatDir {
dirs 'libs'
}
}
I have seen the same error message after upgrading to git1.8.5.2:
Simply make a search for all msys-1.0.dll
on your C:\
drive, and make the one used by Git comes first.
For instance, in my case I simply changed the order of:
C:\prgs\Gow\Gow-0.7.0\bin\msys-1.0.dll
C:\prgs\git\PortableGit-1.8.5.2-preview20131230\bin\msys-1.0.dll
By making the Git path C:\prgs\git\PortableGit-1.8.5.2-preview20131230\bin\
come first in my %PATH%
, the error message disappeared.
No need to reboot or to even change the DOS session.
Once the %PATH%
is updated in that DOS session, the git commands just work.
Note that carmbrester and Sixto Saez both report below (in the comments) having to reboot in order to fix the issue.
Note: First, also removing any msys-1.0.dll
, like one in %LOCALAPPDATA%
GRANT
s on different objects are separate. GRANT
ing on a database doesn't GRANT
rights to the schema within. Similiarly, GRANT
ing on a schema doesn't grant rights on the tables within.
If you have rights to SELECT
from a table, but not the right to see it in the schema that contains it then you can't access the table.
The rights tests are done in order:
Do you have `USAGE` on the schema?
No: Reject access.
Yes: Do you also have the appropriate rights on the table?
No: Reject access.
Yes: Check column privileges.
Your confusion may arise from the fact that the public
schema has a default GRANT
of all rights to the role public
, which every user/group is a member of. So everyone already has usage on that schema.
The phrase:
(assuming that the objects' own privilege requirements are also met)
Is saying that you must have USAGE
on a schema to use objects within it, but having USAGE
on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.
It's like a directory tree. If you create a directory somedir
with file somefile
within it then set it so that only your own user can access the directory or the file (mode rwx------
on the dir, mode rw-------
on the file) then nobody else can list the directory to see that the file exists.
If you were to grant world-read rights on the file (mode rw-r--r--
) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.
If you instead set rwx-r-xr-x
on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.
You need to set both permissions for people to actually be able to view the file.
Same thing in Pg. You need both schema USAGE
rights and object rights to perform an action on an object, like SELECT
from a table.
(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECT
ing from pg_class
directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)
ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.
For this error you can also define a version range:
yarn add typescript@">=3.4.0 <3.6.0" --save-dev --save-exact
or for npm
npm install typescript@">=3.4.0 <3.6.0" --save-dev --save-exact
After installing the correct typescript version:
node_modules
folderyarn install
or npm install
i wrote a simple progressbar:
def bar(total, current, length=10, prefix="", filler="#", space=" ", oncomp="", border="[]", suffix=""):
if len(border) != 2:
print("parameter 'border' must include exactly 2 symbols!")
return None
print(prefix + border[0] + (filler * int(current / total * length) +
(space * (length - int(current / total * length)))) + border[1], suffix, "\r", end="")
if total == current:
if oncomp:
print(prefix + border[0] + space * int(((length - len(oncomp)) / 2)) +
oncomp + space * int(((length - len(oncomp)) / 2)) + border[1], suffix)
if not oncomp:
print(prefix + border[0] + (filler * int(current / total * length) +
(space * (length - int(current / total * length)))) + border[1], suffix)
as you can see, it have: length of bar, prefix and suffix, filler, space, text in bar on 100%(oncomp) and borders
here an example:
from time import sleep, time
start_time = time()
for i in range(10):
pref = str((i+1) * 10) + "% "
complete_text = "done in %s sec" % str(round(time() - start_time))
sleep(1)
bar(10, i + 1, length=20, prefix=pref, oncomp=complete_text)
out in progress:
30% [###### ]
out on complete:
100% [ done in 9 sec ]
you can use: content:url("image.jpg")
<style>
.your-class-name{
content: url("http://imgur.com/SZ8Cm.jpg");
}
</style>
<img class="your-class-name" src="..."/>
first convert your array too JSON
while($query->fetch()){
$col[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}
then vonvert back it to array
foreach($col as &$array){
$array = json_decode($array,true);
}
good luck
In your supplementary question you asked if www.example.com/file[/].html
is a valid URL.
That URL isn't valid because a URL is a type of URI and a valid URI must have a scheme like http:
(see RFC 3986).
If you meant to ask if http://www.example.com/file[/].html
is a valid URL then the answer is still no because the square bracket characters aren't valid there.
The square bracket characters are reserved for URLs in this format: http://[2001:db8:85a3::8a2e:370:7334]/foo/bar
(i.e. an IPv6 literal instead of a host name)
It's worth reading RFC 3986 carefully if you want to understand the issue fully.
No need for jQuery! This simple snippet works fine for me. It uses angular.element() to bind window resize event.
/**
* Window resize event handling
*/
angular.element($window).on('resize', function () {
console.log($window.innerWidth);
});
/**
* Window resize unbind event
*/
angular.element($window).off('resize');
vagrant box add my-box file:///d:/path/to/file.box
Has to be in a URL format.
The first constructor in the header should not end with a semicolon. #include <string>
is missing in the header. string
is not qualified with std::
in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream
is broken. I suggest learning C++ before trying to use it.
Let's fix this up:
//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__
#include <iostream>
#include <string>
class Polygone {
public:
// declarations have to end with a semicolon, definitions do not
Polygone(){} // why would we needs this?
Polygone(const std::string& fichier);
};
# endif
and
//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>
Polygone::Polygone(const std::string& nom)
{
std::ifstream fichier (nom, ios::in);
if (fichier.is_open())
{
// keep the scope as tiny as possible
std::string line;
// getline returns the stream and streams convert to booleans
while ( std::getline(fichier, line) )
{
std::cout << line << std::endl;
}
}
else
{
std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
}
}
I crammed everything into one line (bad I know) and had no troubles with it:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test"
ofType:@"html"]
isDirectory:NO]]];
Here is a solution as an extension of [https://stackoverflow.com/a/46644736/10249774]
Bottom panel is pushing main content upwards
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/my_button"
android:layout_marginTop="10dp"
android:onClick="onSlideViewButtonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<LinearLayout
android:id="@+id/main_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main "
android:textSize="70dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main "
android:textSize="70dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main "
android:textSize="70dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main"
android:textSize="70dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main"
android:textSize="70dp"/>
</LinearLayout>
<LinearLayout
android:id="@+id/footer_view"
android:background="#a6e1aa"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="footer content"
android:textSize="40dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="footer content"
android:textSize="40dp" />
</LinearLayout>
</RelativeLayout>
MainActivity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private View footerView;
private View mainView;
private boolean isUp;
private int anim_duration = 700;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
footerView = findViewById(R.id.footer_view);
mainView = findViewById(R.id.main_view);
myButton = findViewById(R.id.my_button);
// initialize as invisible (could also do in xml)
footerView.setVisibility(View.INVISIBLE);
myButton.setText("Slide up");
isUp = false;
}
public void slideUp(View mainView , View footer_view){
footer_view.setVisibility(View.VISIBLE);
TranslateAnimation animate_footer = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
footer_view.getHeight(), // fromYDelta
0); // toYDelta
animate_footer.setDuration(anim_duration);
animate_footer.setFillAfter(true);
footer_view.startAnimation(animate_footer);
mainView.setVisibility(View.VISIBLE);
TranslateAnimation animate_main = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
0, // fromYDelta
(0-footer_view.getHeight())); // toYDelta
animate_main.setDuration(anim_duration);
animate_main.setFillAfter(true);
mainView.startAnimation(animate_main);
}
public void slideDown(View mainView , View footer_view){
TranslateAnimation animate_footer = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
0, // fromYDelta
footer_view.getHeight()); // toYDelta
animate_footer.setDuration(anim_duration);
animate_footer.setFillAfter(true);
footer_view.startAnimation(animate_footer);
TranslateAnimation animate_main = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
(0-footer_view.getHeight()), // fromYDelta
0); // toYDelta
animate_main.setDuration(anim_duration);
animate_main.setFillAfter(true);
mainView.startAnimation(animate_main);
}
public void onSlideViewButtonClick(View view) {
if (isUp) {
slideDown(mainView , footerView);
myButton.setText("Slide up");
} else {
slideUp(mainView , footerView);
myButton.setText("Slide down");
}
isUp = !isUp;
}
}
Starting with API level 18 (Jellybean MR2) you can cancel Notifications other than your own via NotificationListenerService.
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class MyNotificationListenerService extends NotificationListenerService {...}
...
private void clearNotificationExample(StatusBarNotification sbn) {
myNotificationListenerService.cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}
Given your representation, your function is as efficient as can be done. Of course, as noted by others (and as practiced in languages older than Lua), the solution to your real problem is to change representation. When you have tables and you want sets, you turn tables into sets by using the set element as the key and true
as the value. +1 to interjay.