Here's what finally worked for me. You'll have to convert the code to suit your own needs, but this will do it.
$fname = filter_input(INPUT_POST, "name");
$img = filter_input(INPUT_POST, "image");
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$img = base64_decode($img);
file_put_contents($fname, $img);
print "Image has been saved!";
Add position: relative
to .outside
. (https://developer.mozilla.org/en-US/docs/CSS/position)
Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.
The "initial container" would be <body>
, but adding the above makes .outside
positioned.
There is a better solution now: Vertical align anything with just 3 lines of CSS
AFAIK from Eclipse 3.5 M4 on the formatter has an option "Never Join Lines" which preserves user lines breaks. Maybe that does what you want.
Else there is this ugly hack
String query = //
"SELECT FOO, BAR, BAZ" + //
" FROM ABC" + //
" WHERE BAR > 4";
Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:
$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);
Output:
Array
(
[0] => 4
)
Now:
$key = 4;
$value = $array[$key];
print $value;
Output:
Hello There
Is there any advantage in creating a temporary file in a more careful way
The temporary files are usually created in the temporary directory (such as /tmp
) where all other users and processes has read and write access (any other script can create the new files there). Therefore the script should be careful about creating the files such as using with the right permissions (e.g. read only for the owner, see: help umask
) and filename should be be not easily guessed (ideally random). Otherwise if the filenames aren't unique, it can create conflict with the same script ran multiple times (e.g. race condition) or some attacker could either hijack some sensitive information (e.g. when permissions are too open and filename is easy to guess) or create/replacing the file with their own version of the code (like replacing the commands or SQL queries depending on what is being stored).
You could use the following approach to create the temporary directory:
TMPDIR=".${0##*/}-$$" && mkdir -v "$TMPDIR"
or temporary file:
TMPFILE=".${0##*/}-$$" && touch "$TMPFILE"
However it is still predictable and not considered safe.
As per man mktemp
, we can read:
Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.
So to be safe, it is recommended to use mktemp
command to create unique temporary file or directory (-d
).
Thanks this code was very helpful for me, i found it effective on my projects
$(element).attr('title', 'message').tooltip('fixTitle').tooltip('show');
Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:
private void Calculate(int i)
{
double pow = Math.Pow(i, i);
}
public void DoWork(IProgress<int> progress)
{
// This method is executed in the context of
// another thread (different than the main UI thread),
// so use only thread-safe code
for (int j = 0; j < 100000; j++)
{
Calculate(j);
// Use progress to notify UI thread that progress has
// changed
if (progress != null)
progress.Report((j + 1) * 100 / 100000);
}
}
private async void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = 100;
progressBar1.Step = 1;
var progress = new Progress<int>(v =>
{
// This lambda is executed in context of UI thread,
// so it can safely update form controls
progressBar1.Value = v;
});
// Run operation in another thread
await Task.Run(() => DoWork(progress));
// TODO: Do something after all calculations
}
Tasks are currently the preferred way to implement what BackgroundWorker
does.
Tasks and
Progress
are explained in more detail here:
Ed Webb's answer helped in my case. And instead, you can also try add
@Rule public Mocks mocks = new Mocks(this);
if you @RunWith(JUnit4.class)
.
You can just split the string..
public String[] split(String regex)
Note that java.lang.String.split uses delimiter's regular expression value. Basically like this...
String filename = "abc.def.ghi"; // full file name
String[] parts = filename.split("\\."); // String array, each element is text between dots
String beforeFirstDot = parts[0]; // Text before the first dot
Of course, this is split into multiple lines for clairity. It could be written as
String beforeFirstDot = filename.split("\\.")[0];
You may be able to use the built-in function dir()
to produce similar behavior to PHP's isset()
, something like:
if 'foo' in dir(): # returns False, foo is not defined yet.
pass
foo = 'b'
if 'foo' in dir(): # returns True, foo is now defined and in scope.
pass
dir()
returns a list of the names in the current scope, more information can be found here: http://docs.python.org/library/functions.html#dir.
As long as the server allows the ampresand character to be POSTed (not all do as it can be unsafe), all you should have to do is URL Encode the character. In the case of an ampresand, you should replace the character with %26
.
.NET provides a nice way of encoding the entire string for you though:
string strNew = "&uploadfile=true&file=" + HttpUtility.UrlEncode(iCalStr);
What I did to achieve the goal was to make this..
# I added an extra_command argument that defaults to blank
def save(self, extra_command="", *args, **kwargs):
and below the save() method is this..
# override the save method to create an image thumbnail
if self.image and extra_command != "skip creating photo thumbnail":
# your logic here
so when i edit some fields but not editing the image, I put this..
Model.save("skip creating photo thumbnail")
you can replace the "skip creating photo thumbnail"
with "im just editing the description"
or a more formal text.
Hope this one helps!
You can easily find and remove bin and obj folders in Far Manager.
In search setting dialog:
After the search is done, switch view to "Panel".
Hope it helps someone.
I would just use the request.remote_ip
that's simple and it works. Any reason you need another method?
See: Get real IP address in local Rails development environment for some other things you can do with client server ip's.
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
Look at this example:
public void RunWorker()
{
Thread newThread = new Thread(WorkerMethod);
newThread.Start(new Parameter());
}
public void WorkerMethod(object parameterObj)
{
var parameter = (Parameter)parameterObj;
// do your job!
}
You are first creating a thread by passing delegate to worker method and then starts it with a Thread.Start method which takes your object as parameter.
So in your case you should use it like this:
Thread thread = new Thread(download);
thread.Start(filename);
But your 'download' method still needs to take object, not string as a parameter. You can cast it to string in your method body.
For having a language at Visual Studio Ui , basically the language package of that language must be installed during the installation.
You can not select a language in options -> environment -> international settings that didn't installed.
If the language that you want to select in above path is not appearing than you have to modify your visual studio by re-executing installer and selecting Language Packages tab and check your language that you want to have.
And than at Visual Studio toolbar just click Tools --> Options --> Environment --> International Settings and than select your language from dropdown list.
$("form > .form-group > i").click(function(){
$('#icon').toggleClass('fa-eye fa-eye-slash');
if($('#icon').hasClass('fa-eye')){
$('#Password1').attr('type','text');
} else {
$('#Password1').attr('type','password');
}
});
The problem with changing it via JavaScript or CSS is that if you have a slower connection, the image will take a second to change to the hovered version. This will cause an undesirable flash as one disappears while the other downloads.
What I've done before is have two images. Then hide and show each depending on the hover state. This will allow for a clean switch between the two images.
<a href="/settings">
<img class="default" src="settings-default.svg"/>
<img class="hover" src="settings-hover.svg"/>
<span>Settings</span>
</a>
a img.hover {
display: none;
}
a img.default {
display: inherit;
}
a:hover img.hover {
display: inherit;
}
a:hover img.default {
display: none;
}
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
Try this ...
PropertyInfo isreadonly =typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Remove("foo");
Try JadClipse.It will open all your .class file. Add library to your project and when you try to open any object declared in the lib file it will open just like your .java file.
In eclipse->help-> marketplace -> go to popular tab. There you can find plugins for the same.
Update: For those who are unable to find above plug-in, try downloading this: https://github.com/java-decompiler/jd-eclipse/releases/download/v1.0.0/jd-eclipse-site-1.0.0-RC2.zip
Then import it into Eclipse.
If you have issues importing above plug-in, refer: How to install plugin for Eclipse from .zip
I just added a padding-top to the div below the nav. Hope it helps. I'm new on this. C:
#nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
margin: 0 auto;
padding: 0;
background: url(../css/patterns/black_denim.png);
z-index: 9999;
}
#container {
display: block;
padding: 6em 0 3em;
}
Use GSONBuilder with setPrettyPrinting and disableHtml for nice output.
String json = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().
create().toJson(outputList );
fileOut.println(json);
In my case the solutions above did not work I had to do the following:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));
This happens from time to time in Eclipse. In the "Project" menu there's a "Clean" option, that usually takes care of the problem.
I checked above solutions and found them quite lengthy. It can be accomplished with just one line of code:
currentElement.nextElementSibling.focus();
or
currentElement.previousElementSibling.focus();
here currentElement may be any i.e. document.activeElement or this if current element is in function's context.
I tracked tab and shift-tab events with keydown event Here is a snippet that relies on "JQuery":
let cursorDirection = ''
$(document).keydown(function (e) {
let key = e.which || e.keyCode;
if (e.shiftKey) {
//does not matter if user has pressed tab key or not.
//If it matters for you then compare it with 9
cursorDirection = 'prev';
}
else if (key == 9) {
//if tab key is pressed then move next.
cursorDirection = 'next';
}
else {
cursorDirection == '';
}
});
once you have cursor direction then you can use nextElementSibling.focus
or previousElementSibling.focus
methods
This one works for me:
sudo chown -R $(whoami) ~/.npm
I did not use the -g
because I am the only user. I used a MacBook Air.
If you want the branch too:
gem 'foo', path: "point/to/your/path", branch: "branch-name"
What about support for border radius AND background gradient. Yes IE9 is to support them both seperately but if you mix the two the gradient bleeds out of the rounded corner. Below is a link to a poor example but i have seen it in my own testing as well. Should of taken a screen shot :(
Maybe the real question is when will IE support CSS standards without MS-FILTER proprietary hacks.
http://frugalcoder.us/post/2010/09/15/ie9-corner-plus-gradient-fail.aspx
First set position
of the parent DIV to relative
(specifying the offset, i.e. left
, top
etc. is not necessary) and then apply position: absolute
to the child DIV with the offset you want.
It's simple and should do the trick well.
You can use fprintf/sprintf with familiar C syntax. Maybe something like:
fprintf('x = %d, y = %d \n x+y=%d \n x*y=%d \n x/y=%f\n', x,y,d,e,f)
reading your comment, this is how you use your functions from the main program:
x = 2;
y = 2;
[d e f] = answer(x,y);
fprintf('%d + %d = %d\n', x,y,d)
fprintf('%d * %d = %d\n', x,y,e)
fprintf('%d / %d = %f\n', x,y,f)
Also for the answer() function, you can assign the output values to a vector instead of three distinct variables:
function result=answer(x,y)
result(1)=addxy(x,y);
result(2)=mxy(x,y);
result(3)=dxy(x,y);
and call it simply as:
out = answer(x,y);
In SQL 2017 or higher, you can use this:
declare @hits int = 0
set @hits = (select value from STRING_SPLIT('F609,4DFA,8499',','));
select count(@hits)
https://code.google.com/p/joquery/
Supports different possibilities,
Given collection,
Collection<Dto> testList = new ArrayList<>();
of type,
class Dto
{
private int id;
private String text;
public int getId()
{
return id;
}
public int getText()
{
return text;
}
}
Filter
Java 7
Filter<Dto> query = CQ.<Dto>filter(testList)
.where()
.property("id").eq().value(1);
Collection<Dto> filtered = query.list();
Java 8
Filter<Dto> query = CQ.<Dto>filter(testList)
.where()
.property(Dto::getId)
.eq().value(1);
Collection<Dto> filtered = query.list();
Also,
Filter<Dto> query = CQ.<Dto>filter()
.from(testList)
.where()
.property(Dto::getId).between().value(1).value(2)
.and()
.property(Dto::grtText).in().value(new string[]{"a","b"});
Sorting (also available for the Java 7)
Filter<Dto> query = CQ.<Dto>filter(testList)
.orderBy()
.property(Dto::getId)
.property(Dto::getName)
Collection<Dto> sorted = query.list();
Grouping (also available for the Java 7)
GroupQuery<Integer,Dto> query = CQ.<Dto,Dto>query(testList)
.group()
.groupBy(Dto::getId)
Collection<Grouping<Integer,Dto>> grouped = query.list();
Joins (also available for the Java 7)
Given,
class LeftDto
{
private int id;
private String text;
public int getId()
{
return id;
}
public int getText()
{
return text;
}
}
class RightDto
{
private int id;
private int leftId;
private String text;
public int getId()
{
return id;
}
public int getLeftId()
{
return leftId;
}
public int getText()
{
return text;
}
}
class JoinedDto
{
private int leftId;
private int rightId;
private String text;
public JoinedDto(int leftId,int rightId,String text)
{
this.leftId = leftId;
this.rightId = rightId;
this.text = text;
}
public int getLeftId()
{
return leftId;
}
public int getRightId()
{
return rightId;
}
public int getText()
{
return text;
}
}
Collection<LeftDto> leftList = new ArrayList<>();
Collection<RightDto> rightList = new ArrayList<>();
Can be Joined like,
Collection<JoinedDto> results = CQ.<LeftDto, LeftDto>query().from(leftList)
.<RightDto, JoinedDto>innerJoin(CQ.<RightDto, RightDto>query().from(rightList))
.on(LeftFyo::getId, RightDto::getLeftId)
.transformDirect(selection -> new JoinedDto(selection.getLeft().getText()
, selection.getLeft().getId()
, selection.getRight().getId())
)
.list();
Expressions
Filter<Dto> query = CQ.<Dto>filter()
.from(testList)
.where()
.exec(s -> s.getId() + 1).eq().value(2);
var test_obj = from d in repository.DbPricing
join d1 in repository.DbOfficeProducts on d.OfficeProductId equals d1.Id
join d2 in repository.DbOfficeProductDetails on d1.ProductDetailsId equals d2.Id
select new
{
PricingId = d.Id,
LetterColor = d2.LetterColor,
LetterPaperWeight = d2.LetterPaperWeight
};
http://www.cybertechquestions.com/select-across-multiple-tables-in-entity-framework-resulting-in-a-generic-iqueryable_222801.html
Facade Design Pattern comes under Structural Design Pattern. In short Facade means the exterior appearance. It means in Facade design pattern we hide something and show only what actually client requires. Read more at below blog: http://www.sharepointcafe.net/2017/03/facade-design-pattern-in-aspdotnet.html
In chrome to set the value you need to do YYYY-MM-DD
i guess because this worked : http://jsfiddle.net/HudMe/6/
So to make it work you need to set the date as 2012-10-01
string * and string& differ in a couple of ways. First of all, the pointer points to the address location of the data. The reference points to the data. If you had the following function:
int foo(string *param1);
You would have to check in the function declaration to make sure that param1 pointed to a valid location. Comparatively:
int foo(string ¶m1);
Here, it is the caller's responsibility to make sure the pointed to data is valid. You can't pass a "NULL" value, for example, int he second function above.
With regards to your second question, about the method return values being a reference, consider the following three functions:
string &foo();
string *foo();
string foo();
In the first case, you would be returning a reference to the data. If your function declaration looked like this:
string &foo()
{
string localString = "Hello!";
return localString;
}
You would probably get some compiler errors, since you are returning a reference to a string that was initialized in the stack for that function. On the function return, that data location is no longer valid. Typically, you would want to return a reference to a class member or something like that.
The second function above returns a pointer in actual memory, so it would stay the same. You would have to check for NULL-pointers, though.
Finally, in the third case, the data returned would be copied into the return value for the caller. So if your function was like this:
string foo()
{
string localString = "Hello!";
return localString;
}
You'd be okay, since the string "Hello" would be copied into the return value for that function, accessible in the caller's memory space.
StreamReader reader = new StreamReader(Oldfilepath);
string fileContent = reader.ReadToEnd();
StreamWriter writer = new StreamWriter(NewFilePath);
writer.Write(fileContent);
I think you are looking for this ?
$('#your_id').html('<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>').text();
Create simple ajax combo with de initial seleted value for select2 4.0.3
<select name="mycombo" id="mycombo""></select>
<script>
document.addEventListener("DOMContentLoaded", function (event) {
selectMaker.create('table', 'idname', '1', $("#mycombo"), 2, 'type');
});
</script>
library .js
var selectMaker = {
create: function (table, fieldname, initialSelected, input, minimumInputLength = 3, type ='',placeholder = 'Select a element') {
if (input.data('select2')) {
input.select2("destroy");
}
input.select2({
placeholder: placeholder,
width: '100%',
minimumInputLength: minimumInputLength,
containerCssClass: type,
dropdownCssClass: type,
ajax: {
url: 'ajaxValues.php?getQuery=true&table=' + table + '&fieldname=' + fieldname + '&type=' + type,
type: 'post',
dataType: 'json',
contentType: "application/json",
delay: 250,
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data) {
return {
results: $.map(data.items, function (item) {
return {
text: item.name,
id: item.id
}
})
};
}
}
});
if (initialSelected>0) {
var $option = $('<option selected>Cargando...</option>').val(0);
input.append($option).trigger('change'); // append the option and update Select2
$.ajax({// make the request for the selected data object
type: 'GET',
url: 'ajaxValues.php?getQuery=true&table=' + table + '&fieldname=' + fieldname + '&type=' + type + '&initialSelected=' + initialSelected,
dataType: 'json'
}).then(function (data) {
// Here we should have the data object
$option.text(data.items[0].name).val(data.items[0].id); // update the text that is displayed (and maybe even the value)
$option.removeData(); // remove any caching data that might be associated
input.trigger('change'); // notify JavaScript components of possible changes
});
}
}
};
and the php server side
<?php
if (isset($_GET['getQuery']) && isset($_GET['table']) && isset($_GET['fieldname'])) {
//parametros carga de peticiĆ³n
parse_str(file_get_contents("php://input"), $data);
$data = (object) $data;
if (isset($data->term)) {
$term = pSQL($data->term);
}else{
$term = '';
}
if (isset($_GET['initialSelected'])){
$id =pSQL($_GET['initialSelected']);
}else{
$id = '';
}
if ($_GET['table'] == 'mytable' && $_GET['fieldname'] == 'mycolname' && $_GET['type'] == 'mytype') {
if (empty($id)){
$where = "and name like '%" . $term . "%'";
}else{
$where = "and id= ".$id;
}
$rows = yourarrayfunctionfromsql("SELECT id, name
FROM yourtable
WHERE 1 " . $where . "
ORDER BY name ");
}
$items = array("items" => $rows);
$var = json_encode($items);
echo $var;
?>
Y = y.values[:,0]
Y - formated_train_y
y - train_y
It sounds like more of an architectual issue, and any timeout/disconnect you can do would be more or less a band-aid. This has to be solved on SQL server side, by the way of read-only replica, transaction log shipping (to give you a read-only server to connect to), replication and such. Basically you give the DMZ sql server that heavy read can go to without killing stuff. This is very common. A well-designed SQL system won't be taken down by DDoS - that'd be like a car that dies if you step on the gas.
That said, if you are at the liberty to change the code, you could guesstimate if the query is too heavy and you could either reject or return only X rows in your stored procedure. If you are mated to some reporting tool and such and can't control the SELECT it generates, you could point it to a view and then do the safety valve in the view.
Also, if up-to-the-minute freshness isn't critical and you could compromise on that, like monthly sales data, then compiling a physical table of complex joins by job to avoid complex joins might do the trick - that way everything would be sub-second per query.
It entirely depends on what you are doing, but there is always a solution. Sometimes it takes extra coding to optimize it, sometimes it takes extra money to get you the secondary read-only DB, sometimes it needs time and attention in index tuning.
So it entirely depends, but I'd start with "what can I compromise? what can I change?" and go from there.
Justin's answer is awesome and this response goes into more depth.
The repartition
algorithm does a full shuffle and creates new partitions with data that's distributed evenly. Let's create a DataFrame with the numbers from 1 to 12.
val x = (1 to 12).toList
val numbersDf = x.toDF("number")
numbersDf
contains 4 partitions on my machine.
numbersDf.rdd.partitions.size // => 4
Here is how the data is divided on the partitions:
Partition 00000: 1, 2, 3
Partition 00001: 4, 5, 6
Partition 00002: 7, 8, 9
Partition 00003: 10, 11, 12
Let's do a full-shuffle with the repartition
method and get this data on two nodes.
val numbersDfR = numbersDf.repartition(2)
Here is how the numbersDfR
data is partitioned on my machine:
Partition A: 1, 3, 4, 6, 7, 9, 10, 12
Partition B: 2, 5, 8, 11
The repartition
method makes new partitions and evenly distributes the data in the new partitions (the data distribution is more even for larger data sets).
Difference between coalesce
and repartition
coalesce
uses existing partitions to minimize the amount of data that's shuffled. repartition
creates new partitions and does a full shuffle. coalesce
results in partitions with different amounts of data (sometimes partitions that have much different sizes) and repartition
results in roughly equal sized partitions.
Is coalesce
or repartition
faster?
coalesce
may run faster than repartition
, but unequal sized partitions are generally slower to work with than equal sized partitions. You'll usually need to repartition datasets after filtering a large data set. I've found repartition
to be faster overall because Spark is built to work with equal sized partitions.
N.B. I've curiously observed that repartition can increase the size of data on disk. Make sure to run tests when you're using repartition / coalesce on large datasets.
Read this blog post if you'd like even more details.
When you'll use coalesce & repartition in practice
You can create an array with the size set to a variable, i.e.
int size = 50;
string[] words = new string[size]; // contains 50 strings
However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List
.
Out of curiosity, I ran timings on two of the solutions. The solution which uses a return statement to prematurely end a for loop is slightly more costly on my machine with Python 2.5.1, I suspect this has to do with setting up the iterable.
import random
import timeit
def index_first_item(some_list):
if some_list:
return some_list[0]
def return_first_item(some_list):
for item in some_list:
return item
empty_lists = []
for i in range(10000):
empty_lists.append([])
assert empty_lists[0] is not empty_lists[1]
full_lists = []
for i in range(10000):
full_lists.append(list([random.random() for i in range(10)]))
mixed_lists = empty_lists[:50000] + full_lists[:50000]
random.shuffle(mixed_lists)
if __name__ == '__main__':
ENV = 'import firstitem'
test_data = ('empty_lists', 'full_lists', 'mixed_lists')
funcs = ('index_first_item', 'return_first_item')
for data in test_data:
print "%s:" % data
for func in funcs:
t = timeit.Timer('firstitem.%s(firstitem.%s)' % (
func, data), ENV)
times = t.repeat()
avg_time = sum(times) / len(times)
print " %s:" % func
for time in times:
print " %f seconds" % time
print " %f seconds avg." % avg_time
These are the timings I got:
empty_lists: index_first_item: 0.748353 seconds 0.741086 seconds 0.741191 seconds 0.743543 seconds avg. return_first_item: 0.785511 seconds 0.822178 seconds 0.782846 seconds 0.796845 seconds avg. full_lists: index_first_item: 0.762618 seconds 0.788040 seconds 0.786849 seconds 0.779169 seconds avg. return_first_item: 0.802735 seconds 0.878706 seconds 0.808781 seconds 0.830074 seconds avg. mixed_lists: index_first_item: 0.791129 seconds 0.743526 seconds 0.744441 seconds 0.759699 seconds avg. return_first_item: 0.784801 seconds 0.785146 seconds 0.840193 seconds 0.803380 seconds avg.
I received the same error message. To resolve this I just replaced the Oracle.ManagedDataAccess
assembly with the older Oracle.DataAccess
assembly. This solution may not work if you require new features found in the new assembly. In my case I have many more higher priority issues then trying to configure the new Oracle
assembly.
In general use serialize()
on the form element.
Please be mindful that multiple <select> options are serialized under the same key, e.g.
<select id="foo" name="foo" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
will result in a query string that includes multiple occurences of the same query parameter:
[path]?foo=1&foo=2&foo=3&someotherparams...
which may not be what you want in the backend.
I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):
function compress(data) {
data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}
which turns the above into:
[path]?foo=1,2,3&someotherparams...
In your JS code you'd call it like this:
var inputs = compress($("#your-form").serialize());
Hope that helps.
Personally, I would not place too much emphasis on such "folk wisdom." What may have been true in the past might well not be true now. I would assume that all of the operations relating to a web-page's interpretation and rendering are fully asynchronous ("fetching" something and "acting upon it" are two entirely different things that might be being handled by different threads, etc.), and in any case entirely beyond your control or your concern.
I'd put CSS references in the "head" portion of the document, along with any references to external scripts. (Some scripts may demand to be placed in the body, and if so, oblige them.)
Beyond that ... if you observe that "this seems to be faster/slower than that, on this/that browser," treat this observation as an interesting but irrelevant curiosity and don't let it influence your design decisions. Too many things change too fast. (Anyone want to lay any bets on how many minutes it will be before the Firefox team comes out with yet another interim-release of their product? Yup, me neither.)
I found a way. It's a bit hacky but works.
vm.$set("x",0);
vm.$delete("x");
Where vm
is your view-model object, and x
is a non-existent variable.
Vue.js will complain about this in the console log but it does trigger a refresh for all data. Tested with version 1.0.26.
What is REST
REST stands for representational state transfer, it's actually an architectural style for creating Web API which treats everything(data or functionality) as recourse. It expects; exposing resources through URI and responding in multiple formats and representational transfer of state of the resources in stateless manner. Here I am talking about two things:
REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.SOAP uses services interfaces to expose the business logic. REST uses URI to expose business logic.
REST is not REST without HATEOAS. This means that a client only knows the entry point URI and the resources are supposed to return links the client should follow. Those fancy documentation generators that give URI patterns for everything you can do in a REST API miss the point completely. They are not only documenting something that's supposed to be following the standard, but when you do that, you're coupling the client to one particular moment in the evolution of the API, and any changes on the API have to be documented and applied, or it will break.
HATEOAS, an abbreviation for Hypermedia As The Engine Of Application State, is a constraint of the REST application architecture that distinguishes it from most other network application architectures. The principle is that a client interacts with a network application entirely through hypermedia provided dynamically by application servers. A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia. By contrast, in some service-oriented architectures (SOA), clients and servers interact through a fixed interface shared through documentation or an interface description language (IDL).
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET See @Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
As an alternative to using regex you could do it in Sets:
from sets import Set
allowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
if Set(my_little_sting).issubset(allowed_chars):
# your action
print True
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";
After you use WhenAll
, you can pull the results out individually with await
:
var catTask = FeedCat();
var houseTask = SellHouse();
var carTask = BuyCar();
await Task.WhenAll(catTask, houseTask, carTask);
var cat = await catTask;
var house = await houseTask;
var car = await carTask;
You can also use Task.Result
(since you know by this point they have all completed successfully). However, I recommend using await
because it's clearly correct, while Result
can cause problems in other scenarios.
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
Top down and bottom up DP are two different ways of solving the same problems. Consider a memoized (top down) vs dynamic (bottom up) programming solution to computing fibonacci numbers.
fib_cache = {}
def memo_fib(n):
global fib_cache
if n == 0 or n == 1:
return 1
if n in fib_cache:
return fib_cache[n]
ret = memo_fib(n - 1) + memo_fib(n - 2)
fib_cache[n] = ret
return ret
def dp_fib(n):
partial_answers = [1, 1]
while len(partial_answers) <= n:
partial_answers.append(partial_answers[-1] + partial_answers[-2])
return partial_answers[n]
print memo_fib(5), dp_fib(5)
I personally find memoization much more natural. You can take a recursive function and memoize it by a mechanical process (first lookup answer in cache and return it if possible, otherwise compute it recursively and then before returning, you save the calculation in the cache for future use), whereas doing bottom up dynamic programming requires you to encode an order in which solutions are calculated, such that no "big problem" is computed before the smaller problem that it depends on.
Yes, you can store any object (I assume you are using ASP.NET with default settings, which is in-process session state):
Session["test"] = myList;
You should cast it back to the original type for use:
var list = (List<int>)Session["test"];
// list.Add(something);
As Richard points out, you should take extra care if you are using other session state modes (e.g. SQL Server) that require objects to be serializable.
If you want it visually formatted to two decimals as a string (for output) use toFixed()
:
var priceString = someValue.toFixed(2);
The answer by @David has two problems:
It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999
instead of "134.20"
.
If your value is an integer or rounds to one tenth, you will not see the additional decimal value:
var n = 1.099;
(Math.round( n * 100 )/100 ).toString() //-> "1.1"
n.toFixed(2) //-> "1.10"
var n = 3;
(Math.round( n * 100 )/100 ).toString() //-> "3"
n.toFixed(2) //-> "3.00"
And, as you can see above, using toFixed()
is also far easier to type. ;)
It is possible.
<span ng-if="checked && checked2">
I'm removed when the checkbox is unchecked.
</span>
<Container>
<Menu>
<MenuItem Header="File">
<MenuItem Header="New">
<MenuItem Header="File1"/>
<MenuItem Header="File2"/>
<MenuItem Header="File3"/>
</MenuItem>
<MenuItem Header="Open"/>
<MenuItem Header="Save"/>
</MenuItem>
</Menu>
</Container>
The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldnāt be allowed under the browserās same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS
Open my sql command promt:
then enter mysql password
finally use:
ALTER USER 'username'@'ip_address' IDENTIFIED WITH mysql_native_password BY 'password';
refer:https://stackoverflow.com/a/49228443/6097074
Thanks.
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
Here is a very nifty way.
First format the content such that the column to be compared for uniqueness is a fixed width. One way of doing this is to use awk printf with a field/column width specifier ("%15s").
Now the -f and -w options of uniq can be used to skip preceding fields/columns and to specify the comparison width (column(s) width).
Here are three examples.
In the first example...
1) Temporarily make the column of interest a fixed width greater than or equal to the field's max width.
2) Use -f uniq option to skip the prior columns, and use the -w uniq option to limit the width to the tmp_fixed_width.
3) Remove trailing spaces from the column to "restore" it's width (assuming there were no trailing spaces beforehand).
printf "%s" "$str" \
| awk '{ tmp_fixed_width=15; uniq_col=8; w=tmp_fixed_width-length($uniq_col); for (i=0;i<w;i++) { $uniq_col=$uniq_col" "}; printf "%s\n", $0 }' \
| uniq -f 7 -w 15 \
| awk '{ uniq_col=8; gsub(/ */, "", $uniq_col); printf "%s\n", $0 }'
In the second example...
Create a new uniq column 1. Then remove it after the uniq filter has been applied.
printf "%s" "$str" \
| awk '{ uniq_col_1=4; printf "%15s %s\n", uniq_col_1, $0 }' \
| uniq -f 0 -w 15 \
| awk '{ $1=""; gsub(/^ */, "", $0); printf "%s\n", $0 }'
The third example is the same as the second, but for multiple columns.
printf "%s" "$str" \
| awk '{ uniq_col_1=4; uniq_col_2=8; printf "%5s %15s %s\n", uniq_col_1, uniq_col_2, $0 }' \
| uniq -f 0 -w 5 \
| uniq -f 1 -w 15 \
| awk '{ $1=$2=""; gsub(/^ */, "", $0); printf "%s\n", $0 }'
Some people seem to turn autoescape off which carries security risks to manipulate the string display.
If you only want to insert some linebreaks into a string and convert the linebreaks into <br />
, then you could take a jinja macro like:
{% macro linebreaks_for_string( the_string ) -%}
{% if the_string %}
{% for line in the_string.split('\n') %}
<br />
{{ line }}
{% endfor %}
{% else %}
{{ the_string }}
{% endif %}
{%- endmacro %}
and in your template just call this with
{{ linebreaks_for_string( my_string_in_a_variable ) }}
The finite repetition syntax uses {m,n}
in place of star/plus/question mark.
From java.util.regex.Pattern
:
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
All repetition metacharacter have the same precedence, so just like you may need grouping for *
, +
, and ?
, you may also for {n,m}
.
ha*
matches e.g. "haaaaaaaa"
ha{3}
matches only "haaa"
(ha)*
matches e.g. "hahahahaha"
(ha){3}
matches only "hahaha"
Also, just like *
, +
, and ?
, you can add the ?
and +
reluctant and possessive repetition modifiers respectively.
System.out.println(
"xxxxx".replaceAll("x{2,3}", "[x]")
); "[x][x]"
System.out.println(
"xxxxx".replaceAll("x{2,3}?", "[x]")
); "[x][x]x"
Essentially anywhere a *
is a repetition metacharacter for "zero-or-more", you can use {...}
repetition construct. Note that it's not true the other way around: you can use finite repetition in a lookbehind, but you can't use *
because Java doesn't officially support infinite-length lookbehind.
.*
and .*?
for regexregex{n,}?
== regex{n}
?a{1}b{0,1}
instead of ab?
If we refine the problem talking about testing if a list contains another list with as a sequence, the answer could be the next one-liner:
def contains(subseq, inseq):
return any(inseq[pos:pos + len(subseq)] == subseq for pos in range(0, len(inseq) - len(subseq) + 1))
Here unit tests I used to tune up this one-liner:
Use os.path.join
to concatenate the directory and file name:
for path, subdirs, files in os.walk(root):
for name in files:
print(os.path.join(path, name))
Note the usage of path
and not root
in the concatenation, since using root
would be incorrect.
In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join
would be:
pathlib.PurePath(path, name)
The advantage of pathlib
is that you can use a variety of useful methods on paths. If you use the concrete Path
variant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.
I am not experiented .But i think XmlReader is unnecessary.
It is very hard to use.
XElement is very easy to use.
If you need performance ( faster ) you must change file format and use StreamReader and StreamWriter classes.
convert data-frame to list of dictionary
list_dict = []
for index, row in list(df.iterrows()):
list_dict.append(dict(row))
save file
with open("output.json", mode) as f:
f.write("\n".join(str(item) for item in list_dict))
I have struggled with the matplotlib trimming methods, so I've now just made a function to do this via a bash
call to ImageMagick
's mogrify command, which works well and gets all extra white space off the figure's edge. This requires that you are using UNIX/Linux, are using the bash
shell, and have ImageMagick
installed.
Just throw a call to this after your savefig()
call.
def autocrop_img(filename):
'''Call ImageMagick mogrify from bash to autocrop image'''
import subprocess
import os
cwd, img_name = os.path.split(filename)
bashcmd = 'mogrify -trim %s' % img_name
process = subprocess.Popen(bashcmd.split(), stdout=subprocess.PIPE, cwd=cwd)
This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.
<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com
SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"
VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"
DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
If the PK table is created in one CHARSET and then you create FK table in another CHARSET..then also you might get this error...I too got this error but after changing the charset to PK charset then it got executed without errors
create table users
(
------------
-------------
)DEFAULT CHARSET=latin1;
create table Emp
(
---------
---------
---------
FOREIGN KEY (userid) REFERENCES users(id) on update cascade on delete cascade)ENGINE=InnoDB, DEFAULT CHARSET=latin1;
Running this before the tensorflow
installation solved it for me:
pip install "pip>=19"
As the tensorflow
's system requirements states:
pip 19.0 or later
window.ondragstart = function() { return false; }
If you literally want a one line equivalent to the commands in your original question, you could alias:
mongo --eval "db.getSiblingDB('admin').shutdownServer()"
You can do it in 4 steps:
What you need to type in your terminal:
git revert <commit_hash>
git reset HEAD~1
git add <file_i_want_to_revert>
&& git commit -m 'reverting file'
git checkout .
good luck
Yes you can. The abstract class used in java signifies that you can't create an object of the class. And an abstract method the subclasses have to provide an implementation for that method.
So you can easily define an abstract class without any abstract method.
As for Example :
public abstract class AbstractClass{
public String nonAbstractMethodOne(String param1,String param2){
String param = param1 + param2;
return param;
}
public static void nonAbstractMethodTwo(String param){
System.out.println("Value of param is "+param);
}
}
This is fine.
Multiple column ordering depends on both column's corresponding values: Here is my table example where are two columns named with Alphabets and Numbers and the values in these two columns are asc and desc orders.
Now I perform Order By in these two columns by executing below command:
Now again I insert new values in these two columns, where Alphabet value in ASC order:
and the columns in Example table look like this. Now again perform the same operation:
You can see the values in the first column are in desc order but second column is not in ASC order.
I had the same problem and what ended up being the issue was the RAM size: apparently 1024 (or whatever size) is different from 1024MB. Make sure you specify the units and it should work for you.
Go to the 'style.xml' of your project and make windowActionBar to false
<style name="AppCompatTheme" parent="@style/Theme.AppCompat.Light">
<item name="android:windowActionBar">false</item>
</style>
You canāt call non-static methods from static methods, but by creating an instance inside the static method.
It should work like that
class test2(object):
def __init__(self):
pass
@staticmethod
def dosomething():
print "do something"
# Creating an instance to be able to
# call dosomethingelse(), or you
# may use any existing instance
a = test2()
a.dosomethingelse()
def dosomethingelse(self):
print "do something else"
test2.dosomething()
A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.
Hope, it will help you.
I asked myself the very same questions. When I looked into it I found the choices overwhelming.
Fortunately I found this excellent spreadsheet that helps you choice the best loader based on your requirements:
https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ
ADD following -
It's works for me.
You can do this by AWS S3 Cognito try this link here :
http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-examples.html#Amazon_S3
Also try this code
Just change Region, IdentityPoolId and Your bucket name
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>AWS S3 File Upload</title>_x000D_
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.12.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<input type="file" id="file-chooser" />_x000D_
<button id="upload-button">Upload to S3</button>_x000D_
<div id="results"></div>_x000D_
<script type="text/javascript">_x000D_
AWS.config.region = 'your-region'; // 1. Enter your region_x000D_
_x000D_
AWS.config.credentials = new AWS.CognitoIdentityCredentials({_x000D_
IdentityPoolId: 'your-IdentityPoolId' // 2. Enter your identity pool_x000D_
});_x000D_
_x000D_
AWS.config.credentials.get(function(err) {_x000D_
if (err) alert(err);_x000D_
console.log(AWS.config.credentials);_x000D_
});_x000D_
_x000D_
var bucketName = 'your-bucket'; // Enter your bucket name_x000D_
var bucket = new AWS.S3({_x000D_
params: {_x000D_
Bucket: bucketName_x000D_
}_x000D_
});_x000D_
_x000D_
var fileChooser = document.getElementById('file-chooser');_x000D_
var button = document.getElementById('upload-button');_x000D_
var results = document.getElementById('results');_x000D_
button.addEventListener('click', function() {_x000D_
_x000D_
var file = fileChooser.files[0];_x000D_
_x000D_
if (file) {_x000D_
_x000D_
results.innerHTML = '';_x000D_
var objKey = 'testing/' + file.name;_x000D_
var params = {_x000D_
Key: objKey,_x000D_
ContentType: file.type,_x000D_
Body: file,_x000D_
ACL: 'public-read'_x000D_
};_x000D_
_x000D_
bucket.putObject(params, function(err, data) {_x000D_
if (err) {_x000D_
results.innerHTML = 'ERROR: ' + err;_x000D_
} else {_x000D_
listObjs();_x000D_
}_x000D_
});_x000D_
} else {_x000D_
results.innerHTML = 'Nothing to upload.';_x000D_
}_x000D_
}, false);_x000D_
function listObjs() {_x000D_
var prefix = 'testing';_x000D_
bucket.listObjects({_x000D_
Prefix: prefix_x000D_
}, function(err, data) {_x000D_
if (err) {_x000D_
results.innerHTML = 'ERROR: ' + err;_x000D_
} else {_x000D_
var objKeys = "";_x000D_
data.Contents.forEach(function(obj) {_x000D_
objKeys += obj.Key + "<br>";_x000D_
});_x000D_
results.innerHTML = objKeys;_x000D_
}_x000D_
});_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
The best way to use is white-space: nowrap;
This will align the text to one line.
In C, int
, char
, long
, etc. are all integers.
They typically have different memory sizes and thus different ranges as in INT_MIN
to INT_MAX
. char
and arrays of char
are often used to store characters and strings. Integers are stored in many types: int
being the most popular for a balance of speed, size and range.
ASCII is by far the most popular character encoding, but others exist. The ASCII code for an 'A' is 65, 'a' is 97, '\n' is 10, etc. ASCII data is most often stored in a char
variable. If the C environment is using ASCII encoding, the following all store the same value into the integer variable.
int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;
To convert an int
to a char
, simple assign:
int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4;
This warning comes up because int
typically has a greater range than char
and so some loss-of-information may occur. By using the cast (char)
, the potential loss of info is explicitly directed.
To print the value of an integer:
printf("<%c>\n", c3); // prints <b>
// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>
// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>
printf("<%d>\n", i3); // prints <98>
There are additional issues about printing such as using %hhu
or casting when printing an unsigned char
, but leave that for later. There is a lot to printf()
.
A great way for cloning an array is with an array literal and the spread syntax. This is made possible by ES2015.
const objArray = [{name:'first'}, {name:'second'}, {name:'third'}, {name:'fourth'}];
const clonedArr = [...objArray];
console.log(clonedArr) // [Object, Object, Object, Object]
You can find this copy option in MDN's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Copy_an_array
It is also an Airbnb's best practice. https://github.com/airbnb/javascript#es6-array-spreads
Note: The spread syntax in ES2015 goes one level deep while copying an array. Therefore, they are unsuitable for copying multidimensional arrays.
One of the most easy ways to find where the app is within the simulator. User "NSTemporaryDirectory()"
Steps-
When the app stops at the breakpoint, type following command in Xcode console.
po NSTemporaryDirectory()
See the below image for a proper insight
Now you have the exact path upto temporary folder. You can go back and see all app related folders.
Hope this also helps. Happy Coding :)
I fixed this by running a clean of by gradle build (or delete the gradle build folder mannually)
This occurs if you move the main class to a new package and the old main class is still referenced in the claspath
It is possible to remove duplicates from arraylist without using HashSet or one more arraylist.
Try this code..
ArrayList<String> lst = new ArrayList<String>();
lst.add("ABC");
lst.add("ABC");
lst.add("ABCD");
lst.add("ABCD");
lst.add("ABCE");
System.out.println("Duplicates List "+lst);
Object[] st = lst.toArray();
for (Object s : st) {
if (lst.indexOf(s) != lst.lastIndexOf(s)) {
lst.remove(lst.lastIndexOf(s));
}
}
System.out.println("Distinct List "+lst);
Output is
Duplicates List [ABC, ABC, ABCD, ABCD, ABCE]
Distinct List [ABC, ABCD, ABCE]
Also auto slug at django-admin. Added at ModelAdmin:
prepopulated_fields = {'slug': ('title', )}
As here:
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'slug')
search_fields = ('content', )
prepopulated_fields = {'slug': ('title', )}
Now lets look elasticalsearch table which this tables has duplicated rows and Id is identical uniq field. We know if some id exist by a group criteria then we can delete other rows outscope of this group. My manner shows this criteria.
So many case of this thread are in the like state of mine. Just change your target group criteria according your case for deleting repeated (duplicated) rows.
DELETE
FROM elasticalsearch
WHERE Id NOT IN
(SELECT min(Id)
FROM elasticalsearch
GROUP BY FirmId,FilterSearchString
)
cheers
Container
is itself a template with two type parameters.
Your syntax is incorrect. The var
keyword in your for
loop must be followed by a variable name, in this case its propName
var propValue;
for(var propName in nyc) {
propValue = nyc[propName]
console.log(propName,propValue);
}
I suggest you have a look here for some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
I tried all above, but none working
Finally tried this my own
getBaseActivity().getFragmentManager()
and is working .. :)
On saveAndFlush
, changes will be flushed to DB immediately in this command. With save
, this is not necessarily true, and might stay just in memory, until flush
or commit
commands are issued.
But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.
In your case, you probably use some sort of transactions mechanism, which issues commit
command for you if everything works out fine.
Example code for node.js - async function to sync function:
var deasync = require('deasync');
function syncFunc()
{
var ret = null;
asyncFunc(function(err, result){
ret = {err : err, result : result}
});
while((ret == null))
{
deasync.runLoopOnce();
}
return (ret.err || ret.result);
}
You can use ViewModelBase as base class for all models , this class will take care of pulling data from session
class ViewModelBase
{
public User CurrentUser
{
get { return System.Web.HttpContext.Current.Session["user"] as User };
set
{
System.Web.HttpContext.Current.Session["user"]=value;
}
}
}
You can write a extention method on HttpContextBase to deal with session data
T FromSession<T>(this HttpContextBase context ,string key,Action<T> getFromSource=null)
{
if(context.Session[key]!=null)
{
return (T) context.Session[key];
}
else if(getFromSource!=null)
{
var value = getFromSource();
context.Session[key]=value;
return value;
}
else
return null;
}
Use this like below in controller
User userData = HttpContext.FromSession<User>("userdata",()=> { return user object from service/db });
The second argument is optional it will be used fill session data for that key when value is not present in session.
I've encountered this problem with a input[type="datetime-local"]
, which is similar to this problem.
And I've found a way to overcome this kind of problems.
First, you must turn on chrome's shadow-root feature by "DevTools -> Settings -> General -> Elements -> Show user agent shadow DOM"
Then you can see all shadowed DOM elements, for example, for <input type="number">
, the full element with shadowed DOM is:
<input type="number">_x000D_
<div id="text-field-container" pseudo="-webkit-textfield-decoration-container">_x000D_
<div id="editing-view-port">_x000D_
<div id="inner-editor"></div>_x000D_
</div>_x000D_
<div pseudo="-webkit-inner-spin-button" id="spin"></div>_x000D_
</div>_x000D_
</input>
_x000D_
And according to these info, you can draft some CSS to hide unwanted elements, just as @Josh said.
Just use this constructor of List<T>
. It accepts any IEnumerable<T>
as an argument.
string[] arr = ...
List<string> list = new List<string>(arr);
I'm not using IIS Express but developing against my Local Full IIS 7.
So if anyone else get's here trying to do that, I had to add the mime type for woff via IIS Manager
Mime Types >> Click Add link on right and then enter Extension: .woff MIME type: application/font-woff
With gnuplot using gplot.py
from gplot import *
l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
gplot.log('y')
gplot(*zip(*l))
I had this same issue when transitioning from Bootstrap 2 to 3. I'd already got respond.js and html5shiv.js and set my meta to edge. I'd missed that from 2 to 3 the navbar element type had changed. In Bootstrap 2 it was nav. In Bootstrap 3 it's now header. So to fully resolve the problem I had to
<meta http-equiv="X-UA-Compatible" content="IE=edge">
Put this right after I'd loaded my css:
<!--[if lt IE 9]>
<script src="~/Content/compatibility/html5shiv.js"></script>
<script src="~/Content/compatibility/respond.min.js"></script>
<![endif]-->
and then change
<nav class="navbar" role="navigation">
</nav>
to
<header class="navbar" role="navigation">
</header>
Oh and for good measure I also added
<meta name="viewport" content="width=device-width, initial-scale=1.0">
simply because that's what the Bootstrap site itself has.
Suresh, you don't need use anything in your codes. What you need is just something like this:
.others {_x000D_
color:black_x000D_
}
_x000D_
<select id="select">_x000D_
<option style="color:gray" value="null">select one option</option>_x000D_
<option value="1" class="others">one</option>_x000D_
<option value="2" class="others">two</option>_x000D_
</select>
_x000D_
But as you can see, because your first item in options is the first thing that your select control shows, you can not see its assigned color. While if you open the select list and see the opened items, you will see you could assign a gray color to the first option. So you need something else in jQuery.
$(document).ready(function() {
$('#select').css('color','gray');
$('#select').change(function() {
var current = $('#select').val();
if (current != 'null') {
$('#select').css('color','black');
} else {
$('#select').css('color','gray');
}
});
});
This is my code in jsFiddle.
You can use the createQuery
method (direct in the controller) :
$query = $em->createQuery("SELECT o FROM AcmeCodeBundle:Orders o WHERE o.OrderMail = :ordermail and o.Product like :searchterm")
->setParameter('searchterm', '%'.$searchterm.'%')
->setParameter('ordermail', '[email protected]');
You need to change AcmeCodeBundle to match your bundle name
Or even better - create a repository class for the entity and create a method in there - this will make it reusable
I'm assuming each string in your list contains several words, let me know if that's incorrect.
List<string> list = File.RealAllLines("foobar.txt").ToList();
var words = from line in list
from word in line.Split(new[] { ' ', ';', ',', '.', ':', '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
select word;
var duplicateWords = from w in words
group w by w.ToLower() into g
where g.Count() > 1
select new
{
Word = g.Key,
Count = g.Count()
}
The %d
conversion specifier will only convert one decimal integer. It doesn't know that you're passing an array, it can't modify its behavior based on that. The conversion specifier specifies the conversion.
There is no specifier for arrays, you have to do it explicitly. Here's an example with four conversions:
if(scanf("%d %d %d %d", &array[0], &array[1], &array[2], &array[3]) == 4)
printf("got four numbers\n");
Note that this requires whitespace between the input numbers.
If the id is a single 11-digit number, it's best to treat as a string:
char id[12];
if(scanf("%11s", id) == 1)
{
/* inspect the *character* in id[0], compare with '1' or '2' for instance. */
}
I had the same problem when I created application in Visual Studio, and then in properties created virtual directory for use with local IIS. If someone has this error it is because VS creates application under wrong AppPool, i.e. under AppPool which doesn't suit your needs.
If this is the case, go to IIS Manager, select App, Go to Basic settings and change AppPool for App and you are good to go.
Windows? Unix?
Unix will need a shebang and exec attribute to work:
#!/usr/bin/env python
as the first line of script and:
chmod u+x script.py
at command-line or
call('python script.py'.split())
as mentioned previously.
Windows should work if you add the shell=True parameter to the "call" call.
answer is;
select date_part('year', timestamp '2001-02-16 20:38:40') as year,
date_part('month', timestamp '2001-02-16 20:38:40') as month,
date_part('day', timestamp '2001-02-16 20:38:40') as day,
date_part('hour', timestamp '2001-02-16 20:38:40') as hour,
date_part('minute', timestamp '2001-02-16 20:38:40') as minute
Open a terminal and run these commands:
cd /usr/local/cuda/samples/1_Utilities/deviceQuery
sudo make
./deviceQuery
You can get the information of CUDA Driver version, CUDA Runtime Version, and also detailed information for GPU(s). An image example of the output from my end is as below.
You can also use a pretty simple for
loop:
for f in `find . -not -name "*Music*"`
do
cp $f /target/dir
done
I have created an action in the Accounts
controller that calls a function to create the roles and assign the Admin
role to the default user. (You should probably remove the default user in production):
private async Task CreateRolesandUsers()
{
bool x = await _roleManager.RoleExistsAsync("Admin");
if (!x)
{
// first we create Admin rool
var role = new IdentityRole();
role.Name = "Admin";
await _roleManager.CreateAsync(role);
//Here we create a Admin super user who will maintain the website
var user = new ApplicationUser();
user.UserName = "default";
user.Email = "[email protected]";
string userPWD = "somepassword";
IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);
//Add default User to Role Admin
if (chkUser.Succeeded)
{
var result1 = await _userManager.AddToRoleAsync(user, "Admin");
}
}
// creating Creating Manager role
x = await _roleManager.RoleExistsAsync("Manager");
if (!x)
{
var role = new IdentityRole();
role.Name = "Manager";
await _roleManager.CreateAsync(role);
}
// creating Creating Employee role
x = await _roleManager.RoleExistsAsync("Employee");
if (!x)
{
var role = new IdentityRole();
role.Name = "Employee";
await _roleManager.CreateAsync(role);
}
}
After you could create a controller to manage roles for the users.
In my case, I messed up the connectionString
property in a publish profile, trying to access the wrong database (Initial Catalog
). Entity Framework then complains that the entities do not match the database, and rightly so.
Interesting. The only thing I knew that had to do with programming and had POCO in it is the POCO C++ framework.
Memory in SunHotSpot JVM is organized into three generations: young generation, old generation and permanent generation.
FYI: The permanent gen is not considered a part of the Java heap.
How does the three generations interact/relate to each other? Objects(except the large ones) are first allocated to the young generation. If an object remain alive after x no. of garbage collection cycles it gets promoted to the old/tenured gen. Hence we can say that the young gen contains the short lived objects while the old gen contains the objects having a long life. The permanent gen does not interact with the other two generations.
Take a look also at How do I sort unicode strings alphabetically in Python? where the discussion is about sorting rules given by the Unicode Collation Algorithm (http://www.unicode.org/reports/tr10/).
To reply to the comment
What? How else can ordering be defined other than left-to-right?
by S.Lott, there is a famous counter-example when sorting French language. It involves accents: indeed, one could say that, in French, letters are sorted left-to-right and accents right-to-left. Here is the counter-example: we have e < Ʃ and o < Ɠ, so you would expect the words cote, cotƩ, cƓte, cƓtƩ to be sorted as cote < cotƩ < cƓte < cƓtƩ. Well, this is not what happens, in fact you have: cote < cƓte < cotƩ < cƓtƩ, i.e., if we remove "c" and "t", we get oe < Ɠe < oƩ < ƓƩ, which is exactly right-to-left ordering.
And a last remark: you shouldn't be talking about left-to-right and right-to-left sorting but rather about forward and backward sorting.
Indeed there are languages written from right to left and if you think Arabic and Hebrew are sorted right-to-left you may be right from a graphical point of view, but you are wrong on the logical level!
Indeed, Unicode considers character strings encoded in logical order, and writing direction is a phenomenon occurring on the glyph level. In other words, even if in the word ???? the letter shin appears on the right of the lamed, logically it occurs before it. To sort this word one will first consider the shin, then the lamed, then the vav, then the mem, and this is forward ordering (although Hebrew is written right-to-left), while French accents are sorted backwards (although French is written left-to-right).
Function as lvalue (aka, returning of non-const references) should be removed from C++. It's terribly unintuitive. Scott Meyers wanted a min() with this behavior.
min(a,b) = 0; // What???
which isn't really an improvement on
setmin (a, b, 0);
The latter even makes more sense.
I realize that function as lvalue is important for C++ style streams, but it's worth pointing out that C++ style streams are terrible. I'm not the only one that thinks this... as I recall Alexandrescu had a large article on how to do better, and I believe boost has also tried to create a better type safe I/O method.
iOS 4.3.2's User Agent, which came out this week, is:
Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5
Here's how I've done it ...
1 . make a small script to test if a file is plain text istext:
#!/bin/bash
[[ "$(file -bi $1)" == *"file"* ]]
2 . use find as before
find . -type f -exec istext {} \; -exec grep -nHi mystring {} \;
In my case, on commenting out the
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
in the web.config file was throwing "Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata".
You can know the correct content-type for any file by just doing the following:
1) Select interested file,
2) And run in console this:
console.log($('.file-input')[0].files[0].type);
You can also set attribute "multiple" for your input to check content-type for several files at a time and do next:
for (var i = 0; i < $('.file-input')[0].files.length; i++){
console.log($('.file-input')[0].files[i].type);
}
Attribute accept has some problems with multiple attribute and doesn't work correctly in this case.
I feel like properties are about letting you get the overhead of writing getters and setters only when you actually need them.
Java Programming culture strongly advise to never give access to properties, and instead, go through getters and setters, and only those which are actually needed. It's a bit verbose to always write these obvious pieces of code, and notice that 70% of the time they are never replaced by some non-trivial logic.
In Python, people actually care for that kind of overhead, so that you can embrace the following practice :
@property
to implement them without changing the syntax of the rest of your code.Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.
When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.
If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.
You are passing a dictionary to a function that expects a string.
This syntax:
{"('Hello',)": 6, "('Hi',)": 5}
is both a valid Python dictionary literal and a valid JSON object literal. But loads
doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).
If you pass this string to loads
:
'''{"('Hello',)": 6, "('Hi',)": 5}'''
then it will return a dictionary that looks a lot like the one you are trying to pass to it.
You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:
json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))
But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?
Import lodash
using
$ npm i --save lodash
var _ = require('lodash');
var objArrayList =
[
{ name: "user1"},
{ name: "user2"},
{ name: "user2"}
];
var Obj = _.find(objArrayList, { name: "user2" });
// Obj ==> { name: "user2"}
I had same problem. oddly enough google chrome and possibly others (not sure) did not like
$("#thing").val(0);
input type="hidden" id="thing" name="thing" value="1" />
(no change)
$("#thing").val("0");
input type="hidden" id="thing" name="thing" value="1" />
(no change)
but this works!!!!
$("#thing").val("no");
input type="hidden" id="thing" name="thing" value="no" />
CHANGES!!
$("#thing").val("yes");
input type="hidden" id="thing" name="thing" value="yes" />
CHANGES!!
must be a "string thing"
This is an example, which shows that by converting an int to char, one can determine the corresponding character to an ASCII code.
public class sample6
{
public static void main(String... asf)
{
for(int i =0; i<256; i++)
{
System.out.println( i + ". " + (char)i);
}
}
}
This may be because @GlennMaynard is looking at the matter as in comparison with other languages, but in Python, you do things the python way. It's not a 'why' question. It's there and you can do things to the same effect with x+=
. In The Zen of Python, it is given: "there should only be one way to solve a problem." Multiple choices are great in art (freedom of expression) but lousy in engineering.
If you're getting your timestamps from System.currentTimeMillis()
, then your time variables should be longs.
List<Person> roster = ...;
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(), p -> p)
);
that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)
I have been seeing the exact same error today, but it was not a config or direct JavaScript issue.
An external .net project had been updated but the changes not picked up properly in the compilation of the web site. My presumption is that ASP.NET ajax was not able to construct the client representations of the .NET objects properly and so was failing to load correctly.
To resolve, I rebuilt the external project(s), and rebuilt my solution that was experiencing issues. The problem went away.
It is a generic type parameter, see Generics documentation.
T
is not a reserved keyword. T
, or any given name, means a type parameter. Check the following method (just as a simple example).
T GetDefault<T>()
{
return default(T);
}
Note that the return type is T
. With this method you can get the default value of any type by calling the method as:
GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00
.NET uses generics in collections, ... example:
List<int> integerList = new List<int>();
This way you will have a list that only accepts integers, because the class is instancited with the type T
, in this case int
, and the method that add elements is written as:
public class List<T> : ...
{
public void Add(T item);
}
Some more information about generics.
You can limit the scope of the type T
.
The following example only allows you to invoke the method with types that are classes:
void Foo<T>(T item) where T: class
{
}
The following example only allows you to invoke the method with types that are Circle
or inherit from it.
void Foo<T>(T item) where T: Circle
{
}
And there is new()
that says you can create an instance of T
if it has a parameterless constructor. In the following example T
will be treated as Circle
, you get intellisense...
void Foo<T>(T item) where T: Circle, new()
{
T newCircle = new T();
}
As T
is a type parameter, you can get the object Type
from it. With the Type
you can use reflection...
void Foo<T>(T item) where T: class
{
Type type = typeof(T);
}
As a more complex example, check the signature of ToDictionary
or any other Linq method.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
There isn't a T
, however there is TKey
and TSource
. It is recommended that you always name type parameters with the prefix T
as shown above.
You could name TSomethingFoo
if you want to.
This answer may appear at the surface to be unrelated, but there is an indirect cause of this error message.
First, the "Uses VFP register..." error message is directly caused from mixing mfloat-abi=soft and mfloat-abi=hard options within your build. This setting must be consistent for all objects that are to be linked. This fact is well covered in the other answers to this question.
The indirect cause of this error may be due to the Eclipse editor getting confused by a self-inflicted error in the project's ".cproject" file. The Eclipse editor frequently reswizzles file links and sometimes it breaks itself when you make changes to your directory structures or file locations. This can also affect the path settings to your gcc compiler - and only for a subset of your project's files. While I'm not yet sure of exactly what causes this failure, replacing the .cproject file with a backup copy corrected this problem for me. In my case I noticed .java.null.pointer errors after adding an include directory path and started receiving the "VFP register error" messages out of the blue. In the build log I noticed that a different path to the gcc compiler was being used for some of my sources that were local to the workspace, but not all of them!? The two gcc compilers were using different float settings for unknown reasons - hence the VFP register error.
I compared the .cproject settings with a older copy and observed differences in entries for the sources causing the trouble - even though the overriding of project settings was disabled. By replacing the .cproject file with the old version the problem went away, and I'm leaving this answer as a reminder of what happened.
a[0]
isn't an array, it's the first element of a
and therefore has no dimensions.
Try using a[0:1]
instead, which will return the first element of a
inside a single item array.
There are several problems here:
DateTime.Now
instead of Start
DateTime.Now
is a value of type DateTime
, not Integer
, so the assignment wouldn't work anywayStart
variable anyway; it's doing no goodtotal.Text
is a property of type String
- not DateTime
or Integer
(Some of these would only show up at execution time unless you have Option Strict
on, which you really should.)
You should use:
total.Text = DateTime.Now.ToString()
... possibly specifying a culture and/or format specifier if you want the result in a particular format.
The CSS pointer-events
property alone doesn't disable child elements from scrolling, and it's not supported by IE10 and under for DIV elements (only for SVG).
http://caniuse.com/#feat=pointer-events
To disable the contents of a DIV on all browsers.
Javascript:
$("#myDiv")
.addClass("disable")
.click(function () {
return false;
});
Css:
.disable {
opacity: 0.4;
}
// Disable scrolling on child elements
.disable div,
.disable textarea {
overflow: hidden;
}
To disable the contents of a DIV on all browsers, except IE10 and under.
Javascript:
$("#myDiv").addClass("disable");
Css:
.disable {
// Note: pointer-events not supported by IE10 and under
pointer-events: none;
opacity: 0.4;
}
// Disable scrolling on child elements
.disable div,
.disable textarea {
overflow: hidden;
}
from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))
Although I am not aware if it's officially documented anywhere, you can do footer notes in Github.
Mark the place where you want to insert footer link with a number enclosed in square brackets, I.E. [1]
On the bottom of the post, make a reference of the numbered marker and followed by a colon and the link, I.E. [1]: http://www.example.com/link1
And once you preview it, it will be rendered as numbered links in the body of the post.
Give vertical-align:top;
in a
& span
. Like this:
a, span{
vertical-align:top;
}
Check this http://jsfiddle.net/TFPx8/10/
If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.
If you know your Object array contains Strings only, you may also do (instread of calling toString()):
for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];
The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:
Object[] o = new String[10];
String[] s = (String[]) o;
Nathan Lee's answer is perfect. I just wanted to add something about position:absolute;
. If you wanted to use position:absolute;
like you had in your code, you have to think of it as pushing it away from one side of the page.
For example, if you wanted your div
to be somewhere in the bottom, you would have to use position:absolute; top:500px;
. That would push your div
500px from the top of the page. Same rule applies for all other directions.
I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:
String name;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
name = cursor.getString(cursor
.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
input[type="text"], textarea {
background-color : #d1d1d1;
}
Hope that helps :)
Edit: working example, http://jsfiddle.net/C5WxK/
In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).
I usually print the logs on screen and write into a file as well. Hope this helps someone.
f, err := os.OpenFile("/tmp/orders.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
wrt := io.MultiWriter(os.Stdout, f)
log.SetOutput(wrt)
log.Println(" Orders API Called")
command to remove cordova and ionic
sudo npm uninstall -g ionic
if (args[i] == "&")
Ok, let's disect what this does.
args is an array of pointers. So, here you are comparing args[i]
(a pointer) to "&"
(also a pointer). Well, the only way this will every be true is if somewhere you have args[i]="&"
and even then, "&"
is not guaranteed to point to the same place everywhere.
I believe what you are actually looking for is either strcmp
to compare the entire string or your wanting to do if (*args[i] == '&')
to compare the first character of the args[i]
string to the &
character
CREATE PROCEDURE sp_generate_insertscripts
(
@TABLENAME VARCHAR(MAX),
@FILTER_CONDITION VARCHAR(MAX)='' -- where TableId = 5 or some value
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @TABLE_NAME VARCHAR(MAX),
@CSV_COLUMN VARCHAR(MAX),
@QUOTED_DATA VARCHAR(MAX),
@TEXT VARCHAR(MAX),
@FILTER VARCHAR(MAX)
SET @TABLE_NAME=@TABLENAME
SELECT @FILTER=@FILTER_CONDITION
SELECT @CSV_COLUMN=STUFF
(
(
SELECT ',['+ NAME +']' FROM sys.all_columns
WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
is_identity!=1 FOR XML PATH('')
),1,1,''
)
SELECT @QUOTED_DATA=STUFF
(
(
SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns
WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
is_identity!=1 FOR XML PATH('')
),1,1,''
)
SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER
--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT
EXECUTE (@TEXT)
SET NOCOUNT OFF
END
create example script as resp :
#!/bin/bash
http_code=200
mime=text/html
echo -e "HTTP/1.1 $http_code OK\r"
echo "Content-type: $mime"
echo
echo "Set-Cookie: name=F"
then make executable and execute like this.
./resp | nc -l -p 12346
open browser and browse URL: http://localhost:1236 you will see Cookie value which is sent by Browser
[aaa@bbbbbbbb ]$ ./resp | nc -l -p 12346 GET / HTTP/1.1 Host: xxx.xxx.xxx.xxx:12346 Connection: keep-alive Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8,ru;q=0.6 Cookie: name=F
In your n++ editor, you can go to Setting > Shortcut mapper and find all shortcut information as well as you can edit them :)
In order to navigate to a different drive just use
cd /E/Study/Codes
It will solve your problem.
Joining elements in a list space separated:
word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
joined_string = w + joined_string + " "
print(joined_string.rstrim())
You can use mkdir:
#include <sys/stat.h>
#include <sys/types.h>
int result = mkdir("/home/me/test.txt", 0777);
The latest version of the Android SDK ships with two different applications: an SDK Manager and an AVD Manager rather than one single app that was valid when this question was originally asked.
My particular problem was unrelated to the other suggestions. I'm on a network at the moment where HTTPS traffic is mostly disallowed. In order to install the Android Platform Tools I needed to turn on the option to "Force https://... sources to be fetched using http://..." and then this allowed me to install the other tools.
If you are using appcompat-v7:22.1.0+
you can use the DrawableCompat to tint your widgets
public static void tintWidget(View view, int color) {
Drawable wrappedDrawable = DrawableCompat.wrap(view.getBackground());
DrawableCompat.setTint(wrappedDrawable.mutate(), getResources().getColor(color));
view.setBackgroundDrawable(wrappedDrawable);
}
To see a list of HTTP request headers, you can use :
console.log(JSON.stringify(req.headers));
to return a list in JSON format.
{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}
You can try as follows:
//------ js/functions.js ------
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ js/main.js ------
import { square, diag } from './functions.js';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
You can also import completely:
//------ js/main.js ------
import * as lib from './functions.js';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
Normally we use ./fileName.js
for importing own js file/module
and fileName.js
is used for importing package/library
module
When you will include the main.js file to your webpage you must set the type="module" attribute as follows:
<script type="module" src="js/main.js"></script>
For more details please check ES6 modules
From the Haskell Wiki:
Haskell has a diverse range of use commercially, from aerospace and defense, to finance, to web startups, hardware design firms and lawnmower manufacturers. This page collects resources on the industrial use of Haskell.
According to Wikipedia, the Haskell language was created out of the need to consolidate existing functional languages into a common one which could be used for future research in functional-language design.
It is apparent based on the information available that it has outgrown it's original purpose and is used for much more than research. It is now considered a general purpose functional programming language.
If you're still asking yourself, "Why should I use it?", then read the Why use it? section of the Haskell Wiki Introduction.
Note that if you use Android Studio and download through its SDK Manager, the SDK is downloaded to ~/Library/Android/sdk
by default, not ~/.android-sdk-macosx
.
I would rather add this as a comment to @brismuth's excellent answer, but it seems I don't have enough reputation points yet.
I like atn's answer, but it was not as trivial for me to download as wintee, which is also open source and only gives the tee functionality (useful if you just want tee and not the entire set of unix utilities). I learned about this from davor's answer to Displaying Windows command prompt output and redirecting it to a file, where you also find reference to the unix utilities.
The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min
Therefore there is no difference between default(DateTime)
and new DateTime()
and DateTime.Min
I prefer the third solution, i.e. using 1 and 0, because it is particularly useful when you have to test if a condition is true or false: you can simply use a variable for the if argument.
If you use other methods, I think that, to be consistent with the rest of the code, I should use a test like this:
if (variable == TRUE)
{
...
}
instead of:
if (variable)
{
...
}
If you don't have DBA rights then you can use user_segments table:
select bytes/1024/1024 MB from user_segments where segment_name='Table_name'
I built a Bash debugger. Just give it a try. I hope it will help https://sourceforge.net/projects/bashdebugingbash
What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon
In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.
If you are in ubuntu 12+ get compiz settings manager, in accessibility enable negative, set the shortcuts. The default is super+n. Now make eclipse be in focus and press the super+n or the key you set it as. This will apply negative filter on eclipse.
Are you sure you should be using POST not PUT?
POST is usually used with application/x-www-urlencoded
formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data
. Not always, but usually, that is the right thing to do..
Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.
My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity
, call finish()
. When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.
In my situation, the problem was due to running powershell as an admin, so it was looking for the aws credentials in the root of my admin user. There's probably a better way to resolve this, but what worked quickly for me was recreating my .aws folder in the root of my admin user.
HTML:
<form method="get">
<input type="text" name="id" value="123"/>
<input type="submit" name="action" value="add"/>
<input type="submit" name="action" value="delete"/>
</form>
JS:
$('form').submit(function(ev){
ev.preventDefault();
console.log('clicked',ev.originalEvent,ev.originalEvent.explicitOriginalTarget)
})
Here's a way that allows for ties for the cut-off score.
author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')
You may get more than 30 authors in top_authors this way and the min(30,author_count)
is there incase you have fewer than 30 authors.
<?php
function demo($val,$val1){
return $arr=array("value"=>$val,"value1"=>$val1);
}
$arr_rec=demo(25,30);
echo $arr_rec["value"];
echo $arr_rec["value1"];
?>
For me both answers worked.
<Context docBase="/tmp/wars/hpong" path="" reloadable="true" />
<Service name="Catalina2"> <Connector port="8070" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8743" /> <Engine name="Catalina2" defaultHost="localhost"> <Host name="localhost" unpackWARs="true" autoDeploy="true"> <Context path="" docBase="/tmp/wars/hpong" reloadable="true"> <WatchedResource>WEB-INF/web.xml</WatchedResource> </Context> </Host> </Engine> </Service>
Note: when you declare docBase under context then ignore appBase at Host.
ROOT.war
and place it under webapps. So now unmatched url requests from other wars(contextpaths) will land into this war. This is better way to handle ROOT ("/**") context path. The second option is (double) loading the wars from Webapps folder as well. Also it only needs uncompressed war folder which is a headache.
If you want to add SSL in your test environment, then you can use mkcert
. Below I mentioned the GitHub URL.
https://github.com/FiloSottile/mkcert
And also below I mentioned sample nginx configuration for reverse proxy.
server {
listen 80;
server_name test.local;
return 301 https://test.local$request_uri;
}
server {
listen 443 ssl;
server_name test.local;
ssl_certificate /etc/nginx/ssl/test.local.pem;
ssl_certificate_key /etc/nginx/ssl/test.local-key.pem;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Client-Verify SUCCESS;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://localhost:3000;
proxy_redirect off;
proxy_buffering off;
}
}
UNIX timestamp it is count of seconds from 1970, so you need to convert it to JS Date object:
var date = new Date(unixTimestamp*1000);
I constantly forget the names of the colors I want to use and keep coming back to this question =)
The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.
I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.
I really didn't change much from the matplotlib example, but here is the code for completeness.
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]
n = len(sorted_names)
ncols = 4
nrows = n // ncols
fig, ax = plt.subplots(figsize=(12, 10))
# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols
for i, name in enumerate(sorted_names):
row = i % nrows
col = i // nrows
y = Y - (row * h) - h
xi_line = w * (col + 0.05)
xf_line = w * (col + 0.25)
xi_text = w * (col + 0.3)
ax.text(xi_text, y, name, fontsize=(h * 0.8),
horizontalalignment='left',
verticalalignment='center')
ax.hlines(y + h * 0.1, xi_line, xf_line,
color=colors[name], linewidth=(h * 0.8))
ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()
fig.subplots_adjust(left=0, right=1,
top=1, bottom=0,
hspace=0, wspace=0)
plt.show()
Updated 2017-10-25. I merged my previous updates into this section.
If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:
plt.plot([1,2], lw=4, c='xkcd:baby poop green')
Now you have access to a plethora of named colors!
The default Tableau colors are available in matplotlib via the 'tab:' prefix:
plt.plot([1,2], lw=4, c='tab:green')
There are ten distinct colors:
You can also plot colors by their HTML hex code:
plt.plot([1,2], lw=4, c='#8f9805')
This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...
For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py
.
Simplest way to do so is by adding following code. Tried and Tested.
String[] Array1={"one","two","three"};
ArrayList<String> s1= new ArrayList<String>(Arrays.asList(Array1));
How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids
, but Perl complains.
Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open
returned an error, and make sure you are using use strict; use warnings;
.
my ($ids, $nIds)
is a list, right? With two elements?
It's a (very special) function call. $ids,$nIds
is a list with two elements.
What the code does, is that the number 8000 is counting up from 0 to 8000. The problem is, that it is placed at the middle of quite long page, and once user scroll down and actually see the number, the animation is already dine. I would like to trigger the counter, once it appears in the viewport.
JS:
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
And HTML:
<span class="count">8000</span>
Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:
240p 360p 480p 720p 1080p
Resolution 426 x 240 640 x 360 854x480 1280x720 1920x1080
Video Bitrates
Maximum 700 Kbps 1000 Kbps 2000 Kbps 4000 Kbps 6000 Kbps
Recommended 400 Kbps 750 Kbps 1000 Kbps 2500 Kbps 4500 Kbps
Minimum 300 Kbps 400 Kbps 500 Kbps 1500 Kbps 3000 Kbps
It would appear as though this is the case, although the numbers dont sync up to the google table above:
// the bitrates, video width and file names for this clip
bitrates: [
{ url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
{ url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
{ url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
],
As of 30Jul, 2018 to fix the above issue, one can configure the java version used within maven to any up to JDK/11 and make use of the maven-compiler-plugin:3.8.0
to specify a release of either 9,10,11 without any explicit dependencies.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release> <!--or <release>10</release>-->
</configuration>
</plugin>
Note:- The default value for source/target has been lifted from 1.5 to 1.6 with this version. -- release notes.
Edit [30.12.2018]
In fact, you can make use of the same version of maven-compiler-plugin
while compiling the code against JDK/12 as well.
More details and a sample configuration in how to Compile and execute a JDK preview feature with Maven.
If you are not able to upgrade your Python version to 2.7.9, and want to suppress warnings,
you can downgrade your 'requests' version to 2.5.3:
pip install requests==2.5.3
InetAddress.isReachable()
according to javadoc:
".. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host..".
Option #1 (ICMP) usually requires administrative (root)
rights.
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace OTL
{
/// <summary>
/// Before usage: Define your class, sample:
/// [DataContract]
///public class MusicInfo
///{
/// [DataMember(Name="music_name")]
/// public string Name { get; set; }
/// [DataMember]
/// public string Artist{get; set;}
///}
/// </summary>
/// <typeparam name="T"></typeparam>
public class OTLJSON<T> where T : class
{
/// <summary>
/// Serializes an object to JSON
/// Usage: string serialized = OTLJSON<MusicInfo>.Serialize(musicInfo);
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public static string Serialize(T instance)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, instance);
return Encoding.Default.GetString(stream.ToArray());
}
}
/// <summary>
/// DeSerializes an object from JSON
/// Usage: MusicInfo deserialized = OTLJSON<MusicInfo>.Deserialize(json);
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static T Deserialize(string json)
{
if (string.IsNullOrEmpty(json))
throw new Exception("Json can't empty");
else
try
{
using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(typeof(T));
return serializer.ReadObject(stream) as T;
}
}
catch (Exception e)
{
throw new Exception("Json can't convert to Object because it isn't correct format.");
}
}
}
}
Its workaround.
If you not push to server, you will clone into new folder else washout(delete all files) from your repository folder and clone new.
You can also plot to a png file using gnuplot (which is free):
terminal commands
gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'
note: you always need to give the right extension (.png here) at set output
Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:
plot '<Fromfile.csv>' with line lt -1 lw 2
More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html
apt-get install gnuplot
)brew install gnuplot
)Read the documentation:
with open('names.txt', 'r') as f:
myNames = f.readlines()
The others already provided answers how to get rid of the newline character.
Update:
Fred Larson provides a nice solution in his comment:
with open('names.txt', 'r') as f:
myNames = [line.strip() for line in f]
For most applications you would like to set a minimum level but not a maximum level.
For example, when debugging your code set the minimum level to DEBUG, and in production set it to WARN.
This question has been answered already several times, I'll short summary for each of them, an example and insights as of September 2019:
Example: <h1>
tag inside <section>
by default Google Chrome will make smaller than the "expected" size of <h1>
tag. Microsoft Edge on the other hand is making the "expected" size of <h1>
tag. Normalize.css will make it consistent.
Current status: the npm repository shows that normalize.css package has currently more than 500k downloads per week. GitHub stars in the project of the repository are more than 36k.
Example: it would do something like that below:
html, body, div, span, ..., audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
Current status: it's much less popular than Normalize.css, the reset-css package shows it's something around 26k downloads per week. GitHub stars are only 200, as it can be noticed from the project's repository.
Zero is false, nonzero is true.
In php you can test more explicitly using the ===
operator.
if (0==false)
echo "works"; // will echo works
if (0===false)
echo "works"; // will not echo anything
Try using this command : (this will stop tomcat servlet this really helps)
sudo service tomcat7 stop
or
sudo tomcat7 restart (if you need a restart)
In short:
In MySQL Workbench 6.0+
With this setting you will be able to concatenate fields without getting blobs.
I think this applies to versions 5.2.22 and later and is the result of this MySQL bug.
Disclaimer: I don't know what the downside of this setting is - maybe when you are selecting BINARY
/VARBINARY
values you will see it as plain text which may be misleading and/or maybe it will hinder performance if they are large enough?
Really surprised nobody has mentioned gopkg.in.
gopkg.in
is a service that provides a wrapper (redirect) that lets you express versions as repo urls, without actually creating repos. E.g. gopkg.in/yaml.v1
vs gopkg.in/yaml.v2
, even though they both live at https://github.com/go-yaml/yaml
This isn't perfect if the author is not following proper versioning practices (by incrementing the version number when breaking backwards compatibility), but it does work with branches and tags.