I tried using MP4Box for this task, but it couldn't handle the M4V I was dealing with. I had success embedding the SRT as soft subtitles with ffmpeg with the following command line:
ffmpeg -i input.m4v -i input.srt -vcodec copy -acodec copy -scodec copy -map 0:0 -map 0:1 -map 1:0 -y output.mkv
Like you I had to use an MKV output file - I wasn't able to create an M4V file.
ax.set_title()
should set the titles for separate subplots:
import matplotlib.pyplot as plt
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
fig = plt.figure()
fig.suptitle("Title for whole figure", fontsize=16)
ax = plt.subplot("211")
ax.set_title("Title for first plot")
ax.plot(data)
ax = plt.subplot("212")
ax.set_title("Title for second plot")
ax.plot(data)
plt.show()
Can you check if this code works for you? Maybe something overwrites them later?
You could use this sample code:
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ringtoneSound = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri)
if (ringtoneSound != null) {
ringtoneSound.play();
}
No, it certainly is not. It is just another variable name. The $()
you're talking about is actually the jQuery core function. The $self
is just a variable. You can even rename it to foo
if you want, this doesn't change things. The $
(and _
) are legal characters in a Javascript identifier.
Why this is done so is often just some code convention or to avoid clashes with reversed keywords. I often use it for $this
as follows:
var $this = $(this);
var spl = item.Split('/')[1];
var format =spl.Split(';')[0];
stringconvert=item.Replace($"data:image/{format};base64,",String.Empty);
I always use the return value to pass back error status. If you need to pass back one value I'd use an output parameter.
sample stored procedure, with an OUTPUT parameter:
CREATE PROCEDURE YourStoredProcedure
(
@Param1 int
,@Param2 varchar(5)
,@Param3 datetime OUTPUT
)
AS
IF ISNULL(@Param1,0)>5
BEGIN
SET @Param3=GETDATE()
END
ELSE
BEGIN
SET @Param3='1/1/2010'
END
RETURN 0
GO
call to the stored procedure, with an OUTPUT parameter:
DECLARE @OutputParameter datetime
,@ReturnValue int
EXEC @ReturnValue=YourStoredProcedure 1,null, @OutputParameter OUTPUT
PRINT @ReturnValue
PRINT CONVERT(char(23),@OutputParameter ,121)
OUTPUT:
0
2010-01-01 00:00:00.000
git checkout --[ours/theirs] .
will do what you want, as long as you're at the root of all conflicts. ours/theirs only affects unmerged files so you shouldn't have to grep/find/etc conflicts specifically.
Passed parameter like below,
Param([parameter(Mandatory=$true,
HelpMessage="Enter name and key values")]
$Name,
$Key)
.\script_name.ps1 -Name name -Key key
You can convert a number to a string with n decimal places using the SPRINTF command:
>> x = 1.23; >> sprintf('%0.6f', x) ans = 1.230000 >> x = 1.23456789; >> sprintf('%0.6f', x) ans = 1.234568
Go to "Run" and execute this:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
NOTE: run as administrator.
You could conceivably set up a git hook that when say a commit is made to say the "stable" branch it will pull the changes and apply them to the PHP site. The big downside is you won't have much control if something goes wrong and it will add time to your testing - but you can get an idea of how much work will be involved when you merge say your trunk branch into the stable branch to know how many conflicts you may run into. It will be important to keep an eye on any files that are site specific (eg. configuration files) unless you solely intend to only run the one site.
Alternatively have you looked into pushing the change to the site instead?
For information on git hooks see the githooks documentation.
I fixed it by overriding the hasError method from DefaultResponseErrorHandler class:
public class BadRequestSafeRestTemplateErrorHandler extends DefaultResponseErrorHandler
{
@Override
protected boolean hasError(HttpStatus statusCode)
{
if(statusCode == HttpStatus.BAD_REQUEST)
{
return false;
}
return statusCode.isError();
}
}
And you need to set this handler for restemplate bean:
@Bean
protected RestTemplate restTemplate(RestTemplateBuilder builder)
{
return builder.errorHandler(new BadRequestSafeRestTemplateErrorHandler()).build();
}
If you want to confirm if focus is with an element then
if ($('#inputId').is(':focus')) {
//your code
}
I was having problems here (i.e. sending form-data whilst uploading a file) until I used the following:
files = {'file': (filename, open(filepath, 'rb'), 'text/xml'),
'Content-Disposition': 'form-data; name="file"; filename="' + filename + '"',
'Content-Type': 'text/xml'}
That's the input that ended up working for me. In Chrome Dev Tools -> Network tab, I clicked the request I was interested in. In the Headers tab, there's a Form Data section, and it showed both the Content-Disposition and the Content-Type headers being set there.
I did NOT need to set headers in the actual requests.post() command for this to succeed (including them actually caused it to fail)
Here is my solution:
<!-- jquery smooth scroll to id's -->
<script>
$(function() {
$('a[href*=\\#]:not([href=\\#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 500);
return false;
}
}
});
});
</script>
With just this snippet you can use an unlimited number of hash-links and corresponding ids without having to execute a new script for each.
I already explained how it works in another thread here: https://stackoverflow.com/a/28631803/4566435 (or here's a direct link to my blog post)
For clarifications, let me know. Hope it helps!
The first thing you may want to confirm is the internet connection. Though, internet issues mostly will say that the repo cannot be accessed.
Ensure you have set up ssh both locally and on your github. See how
Ensure you are using the ssh git remote. If you had cloned the https, just set the url to the ssh url, with this git command git remote set-url origin [email protected]:your-username/your-repo-name.git
If you have set up ssh properly but it just stopped working, do the following:
eval "$(ssh-agent -s)"
ssh-add
If you are still having the issue, check to ensure that you have not deleted the ssh from your github. In a case where the ssh has been deleted from github, you can add it back. Use pbcopy < ~/.ssh/id_rsa.pub
to copy the ssh key and then go to your github ssh setting and add it.
I will recommend you always use ssh. For most teams I've worked with, you can't access the repo (which are mostly private) except you use ssh. For a beginner, it may appear to be harder but later you'll find it quite easier and more secured.
It is because * is used as a metacharacter to signify one or more occurences of previous character. So if i write M* then it will look for files MMMMMM..... ! Here you are using * as the only character so the compiler is looking for the character to find multiple occurences of,so it throws the exception.:)
For Intellij users, my issue was that the directory where I had my fxml files (src/main/resources), was not marked as a "Resources" directory.
Open up the module/project settings go to the sources tab and ensure that Intellij knows that the directory contains project resource files.
Do doubles always have 16 significant figures while floats always have 7 significant figures?
No. Doubles always have 53 significant bits and floats always have 24 significant bits (except for denormals, infinities, and NaN values, but those are subjects for a different question). These are binary formats, and you can only speak clearly about the precision of their representations in terms of binary digits (bits).
This is analogous to the question of how many digits can be stored in a binary integer: an unsigned 32 bit integer can store integers with up to 32 bits, which doesn't precisely map to any number of decimal digits: all integers of up to 9 decimal digits can be stored, but a lot of 10-digit numbers can be stored as well.
Why don't doubles have 14 significant figures?
The encoding of a double uses 64 bits (1 bit for the sign, 11 bits for the exponent, 52 explicit significant bits and one implicit bit), which is double the number of bits used to represent a float (32 bits).
I am using Ubuntu 16.04 and for me, it worked by just using two commands:-
ionic cordova platform rm android
ionic cordova platform add [email protected]
Clone is broken, so dont use it.
THE CLONE METHOD of the Object class is a somewhat magical method that does what no pure Java method could ever do: It produces an identical copy of its object. It has been present in the primordial Object superclass since the Beta-release days of the Java compiler*; and it, like all ancient magic, requires the appropriate incantation to prevent the spell from unexpectedly backfiring
Prefer a method that copies the object
Foo copyFoo (Foo foo){
Foo f = new Foo();
//for all properties in FOo
f.set(foo.get());
return f;
}
Read more http://adtmag.com/articles/2000/01/18/effective-javaeffective-cloning.aspx
Looking at the error message, part of the code of your Default.aspx
is :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AmeriaTestTask.Default" %>
but AmeriaTestTask.Default
does not exists, so you have to change it, most probably to the class defined in Default.aspx.cs. For example for web api aplications, the class defined in Global.asax.cs is : public class WebApiApplication : System.Web.HttpApplication
and in the asax page you have :
<%@ Application Codebehind="Global.asax.cs" Inherits="MyProject.WebApiApplication" Language="C#" %>
I have tried all the above solutions. But it was not working in any way.
Finally, I just uninstalled XAMPP and installed it again. Then it worked for me.
Now I am able to run the server on any port (including 80).
You don't need to use the asterisk to accept a list.
Simply give the argument a name in the definition, and pass in a list like
def takes_list(a_list):
for item in a_list:
print item
First record the files you have installed. You can repeat this command, even if you have previously run setup.py install
:
python setup.py install --record files.txt
When you want to uninstall you can just:
sudo rm $(cat files.txt)
This works because the rm command takes a whitespace-seperated list of files to delete and your installation record is just such a list.
There is now one library available that contains unit formatting. I added it to the triava library, as the only other existing library seems to be one for Android.
It can format numbers with arbitrary precision, in 3 different systems (SI, IEC, JEDEC) and various output options. Here are some code examples from the triava unit tests:
UnitFormatter.formatAsUnit(1126, UnitSystem.SI, "B");
// = "1.13kB"
UnitFormatter.formatAsUnit(2094, UnitSystem.IEC, "B");
// = "2.04KiB"
Printing exact kilo, mega values (here with W = Watt):
UnitFormatter.formatAsUnits(12_000_678, UnitSystem.SI, "W", ", ");
// = "12MW, 678W"
You can pass a DecimalFormat to customize the output:
UnitFormatter.formatAsUnit(2085, UnitSystem.IEC, "B", new DecimalFormat("0.0000"));
// = "2.0361KiB"
For arbitrary operations on kilo or mega values, you can split them into components:
UnitComponent uc = new UnitComponent(123_345_567_789L, UnitSystem.SI);
int kilos = uc.kilo(); // 567
int gigas = uc.giga(); // 123
You've added EF to a class library project. You also need to add it to the project that references it (your console app, website or whatever).
Open the Notepad++ as administrator, then import the .dll from the plugin folder that you pasted inside C:Program File/Notepad++/plugins/
In newer versions of Android Studio, the best way to bring in an Eclipse/ADT (Android Development Tool) project is to import it directly into Android Studio; we used to recommend you export it from Eclipse to Gradle first, but we haven't been updating ADT often enough to keep pace with Android Studio.
In any event, if you choose "Import Project" from the File menu or from the Welcome screen when you launch Android Studio, it should take you through a specialized wizard that will prompt you that it intends to copy the files into a new directory structure instead of importing them in-place, and it will offer to fix up some common things like converting dependencies into Maven-style includes and such.
It doesn't seem like you're getting this specialized flow. I think it may not be recognizing your imported project as an ADT project, and it's defaulting to the old built-into-IntelliJ behavior which doesn't know about Gradle. To get the specialized import working, the following must be true:
If your project is complex, perhaps you're not pointing it as the root directory it wants to see for the import to succeed.
Just want to contribute with additional information: I had the same issue and it was because of the field wasn't big enough for the incoming data and this thread helped me to solve it (the top answer clarifies it all).
BUT it is very important to know what are the possible reasons that may cause it.
In my case i was creating the table with a field like this:
Select '' as Period, * From Transactions Into #NewTable
Therefore the field "Period" had a length of Zero and causing the Insert operations to fail. I changed it to "XXXXXX" that is the length of the incoming data and it now worked properly (because field now had a lentgh of 6).
I hope this help anyone with same issue :)
If you want to maintain the order in which you added the elements to the map, use LinkedHashMap
as opposed to just HashMap
.
Here is an approach that will allow you to get a value by its index in the map:
public Object getElementByIndex(LinkedHashMap map,int index){
return map.get( (map.keySet().toArray())[ index ] );
}
EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull : http://www.devart.com/entitydeveloper/editions.html
... or just resultlist.RemoveAt(1)
if you know exactly the index.
This should be OK
$value = explode(".", $value);
$extension = strtolower(array_pop($value)); //Line 32
// the file name is before the last "."
$fileName = array_shift($value); //Line 34
If I want to exit a for-to loop, I just set the index beyond the limit:
For i = 1 To max
some code
if this(i) = 25 Then i = max + 1
some more code...
Next`
Poppa.
By default the PowerShell script execution is very limited for security reasons. For use within NuGet we need to open the doors.
1. Step
Open Windows PowerShell
, run as Administrator
2. Step
NuGet is using the 32 bit console, so it wont be affected by changes to the 64 bit console. Run the following script to make sure you are configuring the 32 bit console.
start-job { Set-ExecutionPolicy RemoteSigned } -RunAs32 | wait-job | Receive-Job
3. Step
Restart Visual Studio
And about timing:
fn1 <- function (N) {
for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
i=1
while (i <= N) {
y <- i*i
i <- i + 1
}
}
system.time(fn1(60000))
# user system elapsed
# 0.06 0.00 0.07
system.time(fn2(60000))
# user system elapsed
# 0.12 0.00 0.13
And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.
In order to verify which branches are merged into master you should use these commands:
git branch <flag[-r/-a/none]> --merged master
list of all branches merged into master.git branch <flag[-r/-a/none]> --merged master | wc -l
count number of all branches merged into master.Flags Are:
-a
flag - (all) showing remote and local branches-r
flag - (remote) showing remote branches only<emptyFlag>
- showing local branches onlyfor example: git branch -r --merged master
will show you all remote repositories merged into master.
In my case node.js
was using some resources in build folder (my app in reactnative
). So I killed node.js
and it solved.
As what I have understand on your question, this is what you want.
Here is a jsFiddle of the below:
$('.childDiv').click(function() {_x000D_
$(this).parent().find('.childDiv').css('background-color', '#ffffff');_x000D_
$(this).css('background-color', '#ff0000');_x000D_
});
_x000D_
.parentDiv {_x000D_
border: 1px solid black;_x000D_
padding: 10px;_x000D_
width: 80px;_x000D_
margin: 5px;_x000D_
display: relative;_x000D_
}_x000D_
.childDiv {_x000D_
border: 1px solid blue;_x000D_
height: 50px;_x000D_
margin: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>_x000D_
<div id="divParent1" class="parentDiv">_x000D_
Group 1_x000D_
<div id="child1" class="childDiv">_x000D_
Child 1_x000D_
</div>_x000D_
<div id="child2" class="childDiv">_x000D_
Child 2_x000D_
</div>_x000D_
</div>_x000D_
<div id="divParent2" class="parentDiv">_x000D_
Group 2_x000D_
<div id="child1" class="childDiv">_x000D_
Child 1_x000D_
</div>_x000D_
<div id="child2" class="childDiv">_x000D_
Child 2_x000D_
</div>_x000D_
</div>
_x000D_
Below is example you can use:
create temp table test2 (
id1 numeric,
id2 numeric,
id3 numeric,
id4 numeric,
id5 numeric,
id6 numeric,
id7 numeric,
id8 numeric,
id9 numeric,
id10 numeric)
with (oids = false);
do
$do$
declare
i int;
begin
for i in 1..100000
loop
insert into test2 values (random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random());
end loop;
end;
$do$;
You can create abstract classes by using object prototypes, a simple example can be as follows :
var SampleInterface = {
addItem : function(item){}
}
You can change above method or not, it is up to you when you implement it. For a detailed observation, you may want to visit here.
It is, generally speaking, a bad idea to compare $(foo) with $(foo) as that is functionally equivalent to the following comparison:
<html>
<head>
<script language='javascript'>
function foo(bar) {
return ({ "object": bar });
}
$ = foo;
if ( $("a") == $("a") ) {
alert ("JS engine screw-up");
}
else {
alert ("Expected result");
}
</script>
</head>
</html>
Of course you would never expect "JS engine screw-up". I use "$" just to make it clear what jQuery is doing.
Whenever you call $("#foo") you are actually doing a jQuery("#foo") which returns a new object. So comparing them and expecting same object is not correct.
However what you CAN do may be is something like:
<html>
<head>
<script language='javascript'>
function foo(bar) {
return ({ "object": bar });
}
$ = foo;
if ( $("a").object == $("a").object ) {
alert ("Yep! Now it works");
}
else {
alert ("This should not happen");
}
</script>
</head>
</html>
So really you should perhaps compare the ID elements of the jQuery objects in your real program so something like
...
$(someIdSelector).attr("id") == $(someOtherIdSelector).attr("id")
is more appropriate.
What about x *= -1;
? Do you really want a library function for this?
Due to the disadvantages described below, I would recommend following the accepted answer:
Use
npm install --save-dev [package_name]
then execute scripts with:$ npm run lint $ npm run build $ npm test
My original but not recommended answer follows.
Instead of using a global install, you could add the package to your devDependencies
(--save-dev
) and then run the binary from anywhere inside your project:
"$(npm bin)/<executable_name>" <arguments>...
In your case:
"$(npm bin)"/node.io --help
This engineer provided an npm-exec
alias as a shortcut. This engineer uses a shellscript called env.sh
. But I prefer to use $(npm bin)
directly, to avoid any extra file or setup.
Although it makes each call a little larger, it should just work, preventing:
sudo
Disadvantages:
$(npm bin)
won't work on Windows.npm bin
folder. (Install npm-run or npm-which to find them.)It seems a better solution is to place common tasks (such as building and minifying) in the "scripts" section of your package.json
, as Jason demonstrates above.
Another mode is: If your editor HAS NO BLOCK comment option,
DONE
it WORKS with ANY editor
Try:
String words[]=temp.split("\\.");
The method is:
String[] split(String regex)
"." is a reserved char in regex
Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.
To clear a canvas, use the delete method. Give it the special parameter "all"
to delete all items on the canvas (the string "all"
" is a special tag that represents all items on the canvas):
canvas.delete("all")
If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all"
, you could supply the name of a tag.
If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.
The quickest way would be with a pivot table. Make sure your column of data has a header row, highlight the data and the header, from the insert ribbon select pivot table and then drag your header from the pivot table fields list to the row labels and to the values boxes.
DT[order(-x)]
works as expected. I have data.table version 1.9.4. Maybe this was fixed in a recent version.
Also, I suggest the setorder(DT, -x)
syntax in keeping with the set* commands like setnames
, setkey
Tips
Remember that the iOS Simulator exploits by default your system language. Please change the language (and region) in the iOS Simulator Setting too in order to test your translations.
The localisation string (see Apple docs here) should be
NSLocationWhenInUseUsageDescription = "Description of this";
and not (with quote "...")
"NSLocationWhenInUseUsageDescription" = "Description of this";
I am not aware of any primitive sorting facilities within the Java core API.
From my experimentations with the D programming language (a sort of C on steroids), I've found that the merge sort algorithm is arguably the fastest general-purpose sorting algorithm around (it's what the D language itself uses to implement its sort function).
I am using Laravel 7.x with blade templating and I use:
<input ... max="{{ now()->toDateString('Y-m-d') }}">
A standard width space for a standard 16px font is 4px.
You set a boolean value in the state (e.g. 'show)', and then do:
var style = {};
if (!this.state.show) {
style.display = 'none'
}
return <div style={style}>...</div>
Using regex:
if re.match(r'^\s*$', line):
# line is empty (has only the following: \t\n\r and whitespace)
Using regex + filter()
:
filtered = filter(lambda x: not re.match(r'^\s*$', x), original)
As seen on codepad.
Another approach to test just for a JSON response (not that the content within contains an expected value), is to parse the response using ActiveSupport:
ActiveSupport::JSON.decode(response.body).should_not be_nil
If the response is not parsable JSON an exception will be thrown and the test will fail.
You are doing Integer division, so you will lose the correct length if the user happens to put in an odd number of inputs - that is one problem I noticed. Because of this, when I run the code with an input of '1,2,3,4,5,6,7' my last value is ignored...
myTest.js
module.exports.get = function () {};
exports.put = function () {};
console.log(module.exports)
// output: { get: [Function], put: [Function] }
exports
and module.exports
are the same and a reference to the same object. You can add properties by both ways as per your convenience.
if x
is a vector with raw scores then scale(x)
is a vector with standardized scores.
Or manually: (x-mean(x))/sd(x)
Your action method considers model type asList<string>
. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>
.
You can solve this problem with changing the model in your view to List<string>
.
But, the best approach would be to return IEnumerable<Standings.Models.Teams>
as a model from your action method. Then you haven't to change model type in your view.
But, in my opinion your models are not correctly implemented. I suggest you to change it as:
public class Team
{
public int Position { get; set; }
public string HomeGround {get; set;}
public string NickName {get; set;}
public int Founded { get; set; }
public string Name { get; set; }
}
Then you must change your action method as:
public ActionResult Index()
{
var model = new List<Team>();
model.Add(new Team { Name = "MU"});
model.Add(new Team { Name = "Chelsea"});
...
return View(model);
}
And, your view:
@model IEnumerable<Standings.Models.Team>
@{
ViewBag.Title = "Standings";
}
@foreach (var item in Model)
{
<div>
@item.Name
<hr />
</div>
}
To schedule the update to be automatic you should:
If you cannot find the Schedule settings, look under: Properties, Edit, Triggers.
I found a solution for this problem after a long analysing procedure.
After properly testing my php installation with the command line features I found out that the php is working well and could work with the mysql database. Btw. you can run code-files with php code with the command php -f filename.php
So I realized, it must something be wrong with the Apache.
I made a file with just the phpinfo() function inside.
Here I saw, that in the line
Loaded Configuration File
my config file was not loaded, instead there was mentioned (none).
Finally I found within the Apache configuration the entry
<IfModule php5_module>
PHPINIDir "C:/xampp/php"
</IfModule>
But I've installed the PHP 7 and so the Apache could not load the php.ini file because there was no entry for that. I added
<IfModule php7_module>
PHPINIDir "C:/xampp/php"
</IfModule>
and after restart Apache all works well.
These code blocks above I found in my httpd-xampp.conf file. May it is somewhere else at your configuration.
In the same file I had changed before the settings for the php 7 as replacement for the php 5 version.
#
# PHP-Module setup
#
#LoadFile "C:/xampp/php/php5ts.dll"
#LoadModule php5_module "C:/xampp/php/php5apache2_4.dll"
LoadFile "C:/xampp/php/php7ts.dll"
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"
As you can see I have the xampp package installed but this problem was just on the Apache side.
@Ciwan. You're right. The table goes to full width (much too wide). Not a good solution. Better to do this:
css:
.scrollme {
overflow-x: auto;
}
html:
<div class="scrollme">
<table class="table table-responsive"> ...
</table>
</div>
Edit: changing scroll-y to scroll-x
This code works for me perfectly
<LinearLayout
android:id="@+id/choosePhotosView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:clickable="true"
android:background="@drawable/transparent_button_bg_rev_selector">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/choose_photo"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:text="@string/choose_photos_tv"/>
</LinearLayout>
I did exactly the same issue using the dependency below:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
I just change to version 46 and everything works.
Also you might want to log in via browser and get the command with all headers including cookies:
Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".
This might work for you:
sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
In order to populate all of the column names into a comma-delimited list for a Select statement for the solutions mentioned for this question, I use the following options as they are a little less verbose than most responses here. Although, most responses here are still perfectly acceptable, however.
1)
SELECT column_name + ','
FROM information_schema.columns
WHERE table_name = 'YourTable'
2) This is probably the simplest approach to creating columns, if you have SQL Server SSMS.
1) Go to the table in Object Explorer and click on the + to the left of the table name or double-click the table name to open the sub list.
2) Drag the column subfolder over to the main query area and it will autopaste the entire column list for you.
Use the LEN
function:
Returns the number of characters of the specified string expression, excluding trailing blanks.
Can do, with jQuery:
$(document).ready(function() {
$('.mandatory').each(function() {
$(this).attr('title', $(this).attr('class'));
});
});
If you want to get current directory path within a file for that you can magic constants __FILE__
and __DIR__
with plugin_dir_path()
function as:
$dir_path = plugin_dir_path( __FILE__ );
CurrentDirectory Path:
/home/user/var/www/wordpress_site/wp-content/plugins/custom-plugin/
__FILE__
magic constant returns current directory path.
If you want to one level up from the current directory. You should use __DIR__
magic constant as:
Current Path:
/home/user/var/www/wordpress_site/wp-content/plugins/custom-plugin/
$dir = plugin_dir_path( __DIR__ );
One level up path:
/home/user/var/www/wordpress_site/wp-content/plugins/
__DIR__
magic constant returns one level up directory path.
based on Sam Holder's answer, you could make an extension method for that
namespace adonet.extensions
{
public static class AdonetExt
{
public static int GetInt32(this SqlDataReader reader, string columnName)
{
return reader.GetInt32(reader.GetOrdinal(columnName));
}
}
}
and use it like this
using adonet.extensions;
//...
int farmsize = reader.GetInt32("farmsize");
assuming there is no GetInt32(string) already in SqlDataReader - if there is any, just use some other method name instead
you can try this in your main Activity , when in the background
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
Check the following project as reference
<div>
<img src="something.jpg" alt="" />
</div>
div {
width: 48px;
height: 48px;
}
div img {
display: block;
width: 100%;
}
This will make the image expand to fill its parent, of which its size is set in the div
CSS.
The answer of @abbotto did not work for me, had to do some things differently:
Add the Git\bin
directory to the Path
environment variable. The directory is %ProgramFiles%\Git\bin
by default. By this way you can access Git Bash with simply typing bash
in every terminal including the integrated terminal of Visual Studio Code.
To revise IIS
Comment:
Platform: Windows Server 2008 R2 Enterprise - 64Bit - IIS 7.5
For performance purpose, here's a little code to benchmark these two alternatives:
#!/bin/python
def hexxorA(a, b):
if len(a) > len(b):
return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a, b[:len(a)])])
def hexxorB(a, b):
if len(a) > len(b):
return '%x' % (int(a[:len(b)],16)^int(b,16))
else:
return '%x' % (int(a,16)^int(b[:len(a)],16))
def testA():
strstr = hexxorA("b4affa21cbb744fa9d6e055a09b562b87205fe73cd502ee5b8677fcd17ad19fce0e0bba05b1315e03575fe2a783556063f07dcd0b9d15188cee8dd99660ee751", "5450ce618aae4547cadc4e42e7ed99438b2628ff15d47b20c5e968f086087d49ec04d6a1b175701a5e3f80c8831e6c627077f290c723f585af02e4c16122b7e2")
if not int(strstr, 16) == int("e0ff3440411901bd57b24b18ee58fbfbf923d68cd88455c57d8e173d91a564b50ce46d01ea6665fa6b4a7ee2fb2b3a644f702e407ef2a40d61ea3958072c50b3", 16):
raise KeyError
return strstr
def testB():
strstr = hexxorB("b4affa21cbb744fa9d6e055a09b562b87205fe73cd502ee5b8677fcd17ad19fce0e0bba05b1315e03575fe2a783556063f07dcd0b9d15188cee8dd99660ee751", "5450ce618aae4547cadc4e42e7ed99438b2628ff15d47b20c5e968f086087d49ec04d6a1b175701a5e3f80c8831e6c627077f290c723f585af02e4c16122b7e2")
if not int(strstr, 16) == int("e0ff3440411901bd57b24b18ee58fbfbf923d68cd88455c57d8e173d91a564b50ce46d01ea6665fa6b4a7ee2fb2b3a644f702e407ef2a40d61ea3958072c50b3", 16):
raise KeyError
return strstr
if __name__ == '__main__':
import timeit
print("Time-it 100k iterations :")
print("\thexxorA: ", end='')
print(timeit.timeit("testA()", setup="from __main__ import testA", number=100000), end='s\n')
print("\thexxorB: ", end='')
print(timeit.timeit("testB()", setup="from __main__ import testB", number=100000), end='s\n')
Here are the results :
Time-it 100k iterations :
hexxorA: 8.139988073991844s
hexxorB: 0.240523161992314s
Seems like '%x' % (int(a,16)^int(b,16))
is faster then the zip version.
First you have to add an ArrayList to the Map
ArrayList<Item> al = new ArrayList<Item>();
Items.add("theKey", al);
then you can add an item to the ArrayLIst that is inside the Map like this:
Items.get("theKey").add(item); // item is an object of type Item
In case anyone else is wondering, you can use is_
to generate foo IS NULL
:
>>> from sqlalchemy.sql import column >>> print column('foo').is_(None) foo IS NULL >>> print column('foo').isnot(None) foo IS NOT NULL
I've solved it another way, if you like.
Here I used two arrays where searchChars containing which will be replaced and replaceChars containing desired characters.
var text = "your input string";_x000D_
var searchChars = ['Å','Ä','å','Ö','ö']; // add more charecter._x000D_
var replaceChars = ['A','A','a','O','o']; // exact same index to searchChars._x000D_
var index;_x000D_
for (var i = 0; i < text.length; i++) {_x000D_
if( $.inArray(text[i], searchChars) >-1 ){ // $.inArray() is from jquery._x000D_
index = searchChars.indexOf(text[i]);_x000D_
text = text.slice(0, i) + replaceChars[index] + text.slice(i+1,text.length);_x000D_
}_x000D_
}
_x000D_
vim may be challenging for beginners. For a quick-and-dirty Windows console-mode text editor, I would suggest Kinesics Text Editor.
I think what are attempting is semantically same as a radio button when 1 is when one of the options is selected and 0 is the other option.
I suggest using the radio button provided by Android by default.
Here is how to use it- http://www.mkyong.com/android/android-radio-buttons-example/
and the android documentation is here-
http://developer.android.com/guide/topics/ui/controls/radiobutton.html
Thanks.
A slight variant of Matthew Dowell's post which avoids the short flash, but displays whenever the contact form 7 form is visible:
div.grecaptcha-badge{
width:0 !important;
}
div.grecaptcha-badge.show{
width:256px !important;
}
I then added the following to the header.php in my child theme:
<script>
jQuery( window ).load(function () {
if( jQuery( '.wpcf7' ).length ){
jQuery( '.grecaptcha-badge' ).addClass( 'show' );
}
});
</script>
The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.
You need to create an int
variable somewhere in memory for the int *
variable to point at.
Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:
int main(){
int variable;
int *ptr = &variable;
*ptr = 20;
printf("%d", *ptr);
return 0;
}
Here, the int
variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20
. The key is that the pointer is initialized to point to the variable
. In fact, you could just allocate some raw memory to point to, if you want:
int main(){
void *memory = malloc(sizeof(int));
int *ptr = (int *)memory;
*ptr = 20;
printf("%d", *ptr);
free(memory);
return 0;
}
When it comes to implement a search functionality there are two suggested approach by official Android Developer Documentation.
You can either use a SearchDialog or a SearchWidget.
I am going to explain the implementation of Search functionality using SearchWidget.
I will explain search functionality in a RecyclerView using SearchWidget. It's pretty straightforward.
Just follow these 5 Simple steps
You can add SearchView
can be added as actionView
in menu using
app:useActionClass = "android.support.v7.widget.SearchView" .
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
android:id="@+id/searchBar"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
You should initialize SearchView in the onCreateOptionsMenu(Menu menu)
method.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search People");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
OnQueryTextListener
has two abstract methods
onQueryTextSubmit(String query)
onQueryTextChange(String newText
So your Activity skeleton would look like this
YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
}
You can provide the implementation for the abstract methods like this
public boolean onQueryTextSubmit(String query) {
// This method can be used when a query is submitted eg. creating search history using SQLite DB
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
Most important part. You can write your own logic to perform search.
Here is mine. This snippet shows the list of Name which contains the text typed in the SearchView
public void filter(String queryText)
{
list.clear();
if(queryText.isEmpty())
{
list.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
list.add(name);
}
}
}
notifyDataSetChanged();
}
Full working code on SearchView with an SQLite database in this Music App
Note to anyone else:
If you have a directory like so, you can add a __main__.py
file to tell the interpreter what to execute if you call the module directly.
my_module
|
| __init__.py
| my_cool_file.py # print "Hello World"
| __main__.py # import my_cool_file
$ python my_module # Hello World
(MacOS) I got this issue after getting some malware that was forcing me to use WeKnow as a search engine. To fix this on MacOs I followed these steps
Go to System Preferences, then check if there's an icon named Profiles.
Remove AdminPrefs profile
Change default search engine settings, Restart Chrome
The above partially helped (I still had WeKnow as my home page). After that I followed these steps:
Type chrome://policy/ to see the policies. You cannot change them there
Copy paste this into your terminal
defaults write com.google.Chrome HomepageIsNewTabPage -bool false
defaults write com.google.Chrome NewTabPageLocation -string "https://www.google.com/"
defaults write com.google.Chrome HomepageLocation -string "https://www.google.com/"
defaults delete com.google.Chrome DefaultSearchProviderSearchURL
defaults delete com.google.Chrome DefaultSearchProviderNewTabURL
defaults delete com.google.Chrome DefaultSearchProviderName
I've also ran a scan of my system with Avast antivirus that has detected some malware
@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow)
OR .Rows.InsertAt(DataRow, Position)
. The following is a stub code which you can modify as per your convenience.
//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";
dt.Rows.Add(dr);//this will add the row at the end of the datatable
//OR
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);
For EditText in image above, You have to create two xml files in res-->drawable folder. First will be "bg_edittext_focused.xml" paste the lines of code in it
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" />
<stroke
android:width="2dip"
android:color="#F6F6F6" />
<corners android:radius="2dip" />
<padding
android:bottom="7dip"
android:left="7dip"
android:right="7dip"
android:top="7dip" />
</shape>
Second file will be "bg_edittext_normal.xml" paste the lines of code in it
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#F6F6F6" />
<stroke
android:width="2dip"
android:color="#F6F6F6" />
<corners android:radius="2dip" />
<padding
android:bottom="7dip"
android:left="7dip"
android:right="7dip"
android:top="7dip" />
</shape>
In res-->drawable folder create another xml file with name "bg_edittext.xml" that will call above mentioned code. paste the following lines of code below in bg_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_edittext_focused" android:state_focused="true"/>
<item android:drawable="@drawable/bg_edittext_normal"/>
</selector>
Finally in res-->layout-->example.xml file in your case wherever you created your editText you'll call bg_edittext.xml as background
<EditText
:::::
:::::
android:background="@drawable/bg_edittext"
:::::
:::::
/>
A pretty safe & concise way to detect IE 11 only is
if(window.msCrypto) {
// I'm IE11 for sure
}
or something like this
var IE11= !!window.msCrypto;
msCrypto
is a prefixed version of the window.crypto
object and only implemented in IE 11.
https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto
Since you mention ReSharper in a comment:
You can do this in ReSharper by using the "Goto File..." option (Ctrl-Shift-N or ReSharper -> Go To -> File...) in my key mappings.
jQuery <1.9
$('#inputId').attr('readonly', true);
jQuery 1.9+
$('#inputId').prop('readonly', true);
Read more about difference between prop and attr
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
There is a fs.readFileSync( path, options )
method, which is synchronous.
You should check if the POST['username']
is defined. Use this above:
$username = "";
if(isset($_POST['username'])){
$username = $_POST['username'];
}
"SELECT password FROM users WHERE username='".$username."'"
HTML:
<div id="parent">
<div class="right"></div>
<div class="left"></div>
</div>
(div.right needs to be before div.left in the HTML markup)
CSS:
.right {
float:right;
width:200px;
}
>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']
In iOS 9.2 they renamed the 'Profiles' to 'Device Management'
This is how you should do it now:
After :
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
You can add (with standard C99 compound literal support) :
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
error("setsockopt(SO_REUSEADDR) failed");
Or :
int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
error("setsockopt(SO_REUSEADDR) failed");
You need to add some arguments. Also, instancing and opening can be put in one line:
fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);
I agree with "too much php", try this:
class Grandpa
{
public function __construct()
{
echo 'Grandpa<br/>';
}
}
class Papa extends Grandpa
{
public function __construct()
{
echo 'Papa<br/>';
parent::__construct();
}
}
class Kiddo extends Papa
{
public function __construct()
{
// THIS IS WHERE I NEED TO CALL GRANDPA'S
// CONSTRUCTOR AND NOT PAPA'S
echo 'Kiddo<br/>';
Grandpa::__construct();
}
}
$instance = new Kiddo;
I got the result as expected:
Kiddo
Grandpa
This is a feature not a bug, check this for your reference:
https://bugs.php.net/bug.php?id=42016
It is just the way it works. If it sees it is coming from the right context this call version does not enforce a static call.
Instead it will simply keep $this and be happy with it.
parent::method() works in the same way, you don't have to define the method as static but it can be called in the same context. Try this out for more interesting:
class Grandpa
{
public function __construct()
{
echo 'Grandpa<br/>';
Kiddo::hello();
}
}
class Papa extends Grandpa
{
public function __construct()
{
echo 'Papa<br/>';
parent::__construct();
}
}
class Kiddo extends Papa
{
public function __construct()
{
// THIS IS WHERE I NEED TO CALL GRANDPA'S
// CONSTRUCTOR AND NOT PAPA'S
echo 'Kiddo<br/>';
Grandpa::__construct();
}
public function hello()
{
echo 'Hello<br/>';
}
}
$instance = new Kiddo;
It also works as expected:
Kiddo
Grandpa
Hello
But if you try to initialize a new Papa, you will get an E_STRICT error:
$papa = new Papa;
Strict standards: Non-static method Kiddo::hello() should not be called statically, assuming $this from incompatible context
You can use instanceof to determine if you can call a Children::method() in a parent method:
if ($this instanceof Kiddo) Kiddo::hello();
Here is a code example which may help:
using System;
using System.Collections.Generic;
using System.Text;
namespace Event_Example
{
// First we have to define a delegate that acts as a signature for the
// function that is ultimately called when the event is triggered.
// You will notice that the second parameter is of MyEventArgs type.
// This object will contain information about the triggered event.
public delegate void MyEventHandler(object source, MyEventArgs e);
// This is a class which describes the event to the class that receives it.
// An EventArgs class must always derive from System.EventArgs.
public class MyEventArgs : EventArgs
{
private string EventInfo;
public MyEventArgs(string Text) {
EventInfo = Text;
}
public string GetInfo() {
return EventInfo;
}
}
// This next class is the one which contains an event and triggers it
// once an action is performed. For example, lets trigger this event
// once a variable is incremented over a particular value. Notice the
// event uses the MyEventHandler delegate to create a signature
// for the called function.
public class MyClass
{
public event MyEventHandler OnMaximum;
private int i;
private int Maximum = 10;
public int MyValue
{
get { return i; }
set
{
if(value <= Maximum) {
i = value;
}
else
{
// To make sure we only trigger the event if a handler is present
// we check the event to make sure it's not null.
if(OnMaximum != null) {
OnMaximum(this, new MyEventArgs("You've entered " +
value.ToString() +
", but the maximum is " +
Maximum.ToString()));
}
}
}
}
}
class Program
{
// This is the actual method that will be assigned to the event handler
// within the above class. This is where we perform an action once the
// event has been triggered.
static void MaximumReached(object source, MyEventArgs e) {
Console.WriteLine(e.GetInfo());
}
static void Main(string[] args) {
// Now lets test the event contained in the above class.
MyClass MyObject = new MyClass();
MyObject.OnMaximum += new MyEventHandler(MaximumReached);
for(int x = 0; x <= 15; x++) {
MyObject.MyValue = x;
}
Console.ReadLine();
}
}
}
Add all threads in collection and submit it using invokeAll
.
If you can use invokeAll
method of ExecutorService
, JVM won’t proceed to next line until all threads are complete.
Here there is a good example: invokeAll via ExecutorService
I use some css like this (based on css tricks):
@media screen and (min-width: 320px) and (max-width: 767px) and (orientation: portrait) {
html {
transform: rotate(-90deg);
transform-origin: left top;
width: 100vh;
height: 100vw;
overflow-x: hidden;
position: absolute;
top: 100%;
left: 0;
}
}
This worked for me:
git remote set-url heroku <repo git>
This replacement old url heroku.
You can check with:
git remote -v
An answer you didn't ask for that may be helpful, if you're doing the replacement in preparation for sending the string into alert() -- or anything else where a single quote character might trip you up.
str.replace("'",'\x27')
That will replace all single quotes with the hex code for single quote.
Use the "not" selector.
For example, instead of:
$(".thumbs").hover()
try:
$(".thumbs:not(.selected)").hover()
You can use Jackson libraries, for binding JSON String into POJO (Plain Old Java Object) instances. POJO is simply a class with only private fields and public getter/setter methods. Jackson is going to traverse the methods (using reflection), and maps the JSON object into the POJO instance as the field names of the class fits to the field names of the JSON object.
In your JSON object, which is actually a composite object, the main object consists o two sub-objects. So, our POJO classes should have the same hierarchy. I'll call the whole JSON Object as Page object. Page object consist of a PageInfo object, and a Post object array.
So we have to create three different POJO classes;
The only package I've used is Jackson ObjectMapper, what we do is binding data;
com.fasterxml.jackson.databind.ObjectMapper
The required dependencies, the jar files is listed below;
Here is the required code;
package com.levo.jsonex.model;
public class Page {
private PageInfo pageInfo;
private Post[] posts;
public PageInfo getPageInfo() {
return pageInfo;
}
public void setPageInfo(PageInfo pageInfo) {
this.pageInfo = pageInfo;
}
public Post[] getPosts() {
return posts;
}
public void setPosts(Post[] posts) {
this.posts = posts;
}
}
package com.levo.jsonex.model;
public class PageInfo {
private String pageName;
private String pagePic;
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getPagePic() {
return pagePic;
}
public void setPagePic(String pagePic) {
this.pagePic = pagePic;
}
}
package com.levo.jsonex.model;
public class Post {
private String post_id;
private String actor_id;
private String picOfPersonWhoPosted;
private String nameOfPersonWhoPosted;
private String message;
private int likesCount;
private String[] comments;
private int timeOfPost;
public String getPost_id() {
return post_id;
}
public void setPost_id(String post_id) {
this.post_id = post_id;
}
public String getActor_id() {
return actor_id;
}
public void setActor_id(String actor_id) {
this.actor_id = actor_id;
}
public String getPicOfPersonWhoPosted() {
return picOfPersonWhoPosted;
}
public void setPicOfPersonWhoPosted(String picOfPersonWhoPosted) {
this.picOfPersonWhoPosted = picOfPersonWhoPosted;
}
public String getNameOfPersonWhoPosted() {
return nameOfPersonWhoPosted;
}
public void setNameOfPersonWhoPosted(String nameOfPersonWhoPosted) {
this.nameOfPersonWhoPosted = nameOfPersonWhoPosted;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getLikesCount() {
return likesCount;
}
public void setLikesCount(int likesCount) {
this.likesCount = likesCount;
}
public String[] getComments() {
return comments;
}
public void setComments(String[] comments) {
this.comments = comments;
}
public int getTimeOfPost() {
return timeOfPost;
}
public void setTimeOfPost(int timeOfPost) {
this.timeOfPost = timeOfPost;
}
}
I've just copied your JSON sample into this file and put it under the project folder.
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
},
"posts": [
{
"post_id": "123456789012_123456789012",
"actor_id": "1234567890",
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": "2",
"comments": [],
"timeOfPost": "1234567890"
}
]
}
package com.levo.jsonex;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.levo.jsonex.model.Page;
import com.levo.jsonex.model.PageInfo;
import com.levo.jsonex.model.Post;
public class JSONDemo {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
Page page = objectMapper.readValue(new File("sampleJSONFile.json"), Page.class);
printParsedObject(page);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void printParsedObject(Page page) {
printPageInfo(page.getPageInfo());
System.out.println();
printPosts(page.getPosts());
}
private static void printPageInfo(PageInfo pageInfo) {
System.out.println("Page Info;");
System.out.println("**********");
System.out.println("\tPage Name : " + pageInfo.getPageName());
System.out.println("\tPage Pic : " + pageInfo.getPagePic());
}
private static void printPosts(Post[] posts) {
System.out.println("Page Posts;");
System.out.println("**********");
for(Post post : posts) {
printPost(post);
}
}
private static void printPost(Post post) {
System.out.println("\tPost Id : " + post.getPost_id());
System.out.println("\tActor Id : " + post.getActor_id());
System.out.println("\tPic Of Person Who Posted : " + post.getPicOfPersonWhoPosted());
System.out.println("\tName Of Person Who Posted : " + post.getNameOfPersonWhoPosted());
System.out.println("\tMessage : " + post.getMessage());
System.out.println("\tLikes Count : " + post.getLikesCount());
System.out.println("\tComments : " + Arrays.toString(post.getComments()));
System.out.println("\tTime Of Post : " + post.getTimeOfPost());
}
}
Page Info;
****(*****
Page Name : abc
Page Pic : http://example.com/content.jpg
Page Posts;
**********
Post Id : 123456789012_123456789012
Actor Id : 1234567890
Pic Of Person Who Posted : http://example.com/photo.jpg
Name Of Person Who Posted : Jane Doe
Message : Sounds cool. Can't wait to see it!
Likes Count : 2
Comments : []
Time Of Post : 1234567890
No need to pass anything in. The function used for addEventListener
will automatically have this
bound to the current element. Simply use this
in your function:
productLineSelect.addEventListener('change', getSelection, false);
function getSelection() {
var value = this.options[this.selectedIndex].value;
alert(value);
}
Here's the fiddle: http://jsfiddle.net/dJ4Wm/
If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:
productLineSelect.addEventListener('change', function() {
foo('bar');
}, false);
function foo(message) {
alert(message);
}
Here's the fiddle: http://jsfiddle.net/t4Gun/
If you want to set the value of this
manually, you can use the call
method to call the function:
var self = this;
productLineSelect.addEventListener('change', function() {
getSelection.call(self);
// This'll set the `this` value inside of `getSelection` to `self`
}, false);
function getSelection() {
var value = this.options[this.selectedIndex].value;
alert(value);
}
A DBA has no freedom to make changes to the data model without forcing you to change your compiled code. With stored procedures, you can hide these sorts of changes to an extent, since the parameter list and results set(s) returned from a procedure represent its contract, and the innards can be changed around, just so long as that contract is still met.
I really don't see this as being a benefit. Being able to change something in isolation might sound good in theory, but just because the changes fulfil a contract doesn't mean it's returning the correct results. To be able to determine what the correct results are you need context and you get that context from the calling code.
In my case the error was caused by the insufficient memory allocated to the "test" lifecycle of maven. It was fixed by adding <argLine>-Xms3512m -Xmx3512m</argLine>
to:
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<argLine>-Xms3512m -Xmx3512m</argLine>
Thanks @crazycoder for pointing this out (and also that it is not related to IntelliJ; in this case).
If your tests are forked, they run in a new JVM that doesn't inherit Maven JVM options. Custom memory options must be provided via the test runner in pom.xml, refer to Maven documentation for details, it has very little to do with the IDE.
Why not set ON CASCADE DELETE on Foreign Key patron_info
.pid?
You can use max-height
in an inline style
attribute, as below:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
To use scrolling with content that overflows a given max-height
, you can alternatively try the following:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>
To restrict the height to a fixed value you can use something like this.
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
Specify the same value for both max-height
and min-height
(either in pixels or in points – as long as it’s consistent).
You can also put the same styles in css class in a stylesheet (or a style
tag as shown below) and then include the same in your tag. See below:
Style Code:
.fixed-panel {
min-height: 10;
max-height: 10;
overflow-y: scroll;
}
Apply Style :
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>
Hope this helps with your need.
The ls
command has a parameter -t
to sort by time. You can then grab the first (newest) with head -1
.
ls -t b2* | head -1
But beware: Why you shouldn't parse the output of ls
My personal opinion: parsing ls
is only dangerous when the filenames can contain funny characters like spaces or newlines. If you can guarantee that the filenames will not contain funny characters then parsing ls
is quite safe.
If you are developing a script which is meant to be run by many people on many systems in many different situations then I very much do recommend to not parse ls
.
Here is how to do it "right": How can I find the latest (newest, earliest, oldest) file in a directory?
unset -v latest
for file in "$dir"/*; do
[[ $file -nt $latest ]] && latest=$file
done
It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.
If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.
You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)
You typically do commit .gitignore
. In fact, I personally go as far as making sure my index is always clean when I'm not working on something. (git status
should show nothing.)
There are cases where you want to ignore stuff that really isn't project specific. For example, your text editor may create automatic *~
backup files, or another example would be the .DS_Store
files created by OS X.
I'd say, if others are complaining about those rules cluttering up your .gitignore
, leave them out and instead put them in a global excludes file.
By default this file resides in $XDG_CONFIG_HOME/git/ignore
(defaults to ~/.config/git/ignore
), but this location can be changed by setting the core.excludesfile
option. For example:
git config --global core.excludesfile ~/.gitignore
Simply create and edit the global excludesfile to your heart's content; it'll apply to every git repository you work on on that machine.
Depending how intrinsic this kind of functionality is to your project, you might want to consider something like MEF which will take care of the loading and tying together of components for you.
I have used sequelize.js
, node.js
and transaction
in below code and added proper error handling if it doesn't find data it will throw error that no data found with that id
editLocale: async (req, res) => {
sequelize.sequelize.transaction(async (t1) => {
if (!req.body.id) {
logger.warn(error.MANDATORY_FIELDS);
return res.status(500).send(error.MANDATORY_FIELDS);
}
let id = req.body.id;
let checkLocale= await sequelize.Locale.findOne({
where: {
id : req.body.id
}
});
checkLocale = checkLocale.get();
if (checkLocale ) {
let Locale= await sequelize.Locale.update(req.body, {
where: {
id: id
}
});
let result = error.OK;
result.data = Locale;
logger.info(result);
return res.status(200).send(result);
}
else {
logger.warn(error.DATA_NOT_FOUND);
return res.status(404).send(error.DATA_NOT_FOUND);
}
}).catch(function (err) {
logger.error(err);
return res.status(500).send(error.SERVER_ERROR);
});
},
Is this what you are trying?
Sub Sample()
Dim cb As Shape
Set cb = ActiveSheet.Shapes("Check Box 1")
If cb.OLEFormat.Object.Value = 1 Then
MsgBox "Checkbox is Checked"
Else
MsgBox "Checkbox is not Checked"
End If
End Sub
Replace Activesheet
with the relevant sheetname. Also replace Check Box 1
with the relevant checkbox name.
You can use markersize to specify the size of the circle in plot method
import numpy as np
import matplotlib.pyplot as plt
x1 = np.random.randn(20)
x2 = np.random.randn(20)
plt.figure(1)
# you can specify the marker size two ways directly:
plt.plot(x1, 'bo', markersize=20) # blue circle with size 10
plt.plot(x2, 'ro', ms=10,) # ms is just an alias for markersize
plt.show()
From here
For me it worked after removing the target
folder
I'm kind of surprised SSL with client certificates hasn't been mentioned yet. Granted, this approach is only really useful if you can count on the community of users being identified by certificates. But a number of governments/companies do issue them to their users. The user doesn't have to worry about creating yet another username/password combination, and the identity is established on each and every connection so communication with the server can be entirely stateless, no user sessions required. (Not to imply that any/all of the other solutions mentioned require sessions)
You can't have a non-keyword argument after a keyword argument.
Make sure you re-arrange your function arguments like so:
def a(len1,til,hgt=len1,col=0):
system('mode con cols='+len1,'lines='+hgt)
system('title',til)
system('color',col)
a(64,"hi",25,"0b")
Although you cannot use different sized slides in one PowerPoint file, for the actual presentation you can link several different files together to create a presentation that has different slide sizes.
The process to do so is as follows:
Reference to Office Support Page where this solution was first posted. https://support.office.com/en-us/article/can-i-use-portrait-and-landscape-slide-orientation-in-the-same-presentation-d8c21781-1fb6-4406-bcd6-25cfac37b5d6?ocmsassetID=HA010099556&CorrelationId=1ac4e97f-bfe6-47b1-bab6-5783e78d126d&ui=en-US&rs=en-US&ad=US
It's called a Favicon, have a read.
<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>
You can use this neat tool to generate cross-browser compatible Favicons.
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];
I found this to be the simplest approach for Django 1.3:
views.py
from local_settings import BASE_URL
def root(request):
return render_to_response('hero.html', {'BASE_URL': BASE_URL})
hero.html
var BASE_URL = '{{ JS_BASE_URL }}';
This should work. While sending the prop back you are sending that as an object rather send that as a value or alternatively use it as an object in the parent component. Secondly you need to format your json object to contain name value pairs and use valueField
and textField
attribute of DropdownList
Short Answer
Parent:
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
Child:
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
Detailed:
EDIT:
Considering React.createClass is deprecated from v16.0 onwards, It is better to go ahead and create a React Component by extending React.Component
. Passing data from child to parent component with this syntax will look like
Parent
class ParentComponent extends React.Component {
state = { language: '' }
handleLanguage = (langValue) => {
this.setState({language: langValue});
}
render() {
return (
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
)
}
}
Child
var json = require("json!../languages.json");
var jsonArray = json.languages;
export class SelectLanguage extends React.Component {
state = {
selectedCode: '',
selectedLanguage: jsonArray[0],
}
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
render() {
return (
<div>
<DropdownList ref={(ref) => this.dropdown = ref}
data={jsonArray}
valueField='lang' textField='lang'
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
}
Using createClass
syntax which the OP used in his answer
Parent
const ParentComponent = React.createClass({
getInitialState() {
return {
language: '',
};
},
handleLanguage: function(langValue) {
this.setState({language: langValue});
},
render() {
return (
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
);
});
Child
var json = require("json!../languages.json");
var jsonArray = json.languages;
export const SelectLanguage = React.createClass({
getInitialState: function() {
return {
selectedCode: '',
selectedLanguage: jsonArray[0],
};
},
handleLangChange: function () {
var lang = this.refs.dropdown.value;
this.props.onSelectLanguage(lang);
},
render() {
return (
<div>
<DropdownList ref='dropdown'
data={jsonArray}
valueField='lang' textField='lang'
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
});
JSON:
{
"languages":[
{
"code": "aaa",
"lang": "english"
},
{
"code": "aab",
"lang": "Swedish"
},
]
}
You can go without the loop:
find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \;
HTH
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
This works for me:
protected boolean isTypeOf(String myClass, Class<?> superClass) {
boolean isSubclassOf = false;
try {
Class<?> clazz = Class.forName(myClass);
if (!clazz.equals(superClass)) {
clazz = clazz.getSuperclass();
isSubclassOf = isTypeOf(clazz.getName(), superClass);
} else {
isSubclassOf = true;
}
} catch(ClassNotFoundException e) {
/* Ignore */
}
return isSubclassOf;
}
Solution with .Where and .Contains has complexity of O(N square). Simple .Join should have a lot better performance (close to O(N) due to hashing). So the correct code is:
_dataContext.UserProfile.Join(idList, up => up.ID, id => id, (up, id) => up);
And now result of my measurement. I generated 100 000 UserProfiles and 100 000 ids. Join took 32ms and .Where with .Contains took 2 minutes and 19 seconds! I used pure IEnumerable for this testing to prove my statement. If you use List instead of IEnumerable, .Where and .Contains will be faster. Anyway the difference is significant. The fastest .Where .Contains is with Set<>. All it depends on complexity of underlying coletions for .Contains. Look at this post to learn about linq complexity.Look at my test sample below:
private static void Main(string[] args)
{
var userProfiles = GenerateUserProfiles();
var idList = GenerateIds();
var stopWatch = new Stopwatch();
stopWatch.Start();
userProfiles.Join(idList, up => up.ID, id => id, (up, id) => up).ToArray();
Console.WriteLine("Elapsed .Join time: {0}", stopWatch.Elapsed);
stopWatch.Restart();
userProfiles.Where(up => idList.Contains(up.ID)).ToArray();
Console.WriteLine("Elapsed .Where .Contains time: {0}", stopWatch.Elapsed);
Console.ReadLine();
}
private static IEnumerable<int> GenerateIds()
{
// var result = new List<int>();
for (int i = 100000; i > 0; i--)
{
yield return i;
}
}
private static IEnumerable<UserProfile> GenerateUserProfiles()
{
for (int i = 0; i < 100000; i++)
{
yield return new UserProfile {ID = i};
}
}
Console output:
Elapsed .Join time: 00:00:00.0322546
Elapsed .Where .Contains time: 00:02:19.4072107
I run into the same problem and learn that queue module defines classes and exceptions, that defines the public methods (Queue Objects).
Ex.
workQueue = queue.Queue(10)
You can use this for fit image at Swift 3;
extension UIImage {
func resizedImage(newSize: CGSize) -> UIImage {
// Guard newSize is different
guard self.size != newSize else { return self }
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
func resizedImageWithinRect(rectSize: CGSize) -> UIImage {
let widthFactor = size.width / rectSize.width
let heightFactor = size.height / rectSize.height
var resizeFactor = widthFactor
if size.height > size.width {
resizeFactor = heightFactor
}
let newSize = CGSize(width: size.width/resizeFactor, height: size.height/resizeFactor)
let resized = resizedImage(newSize: newSize)
return resized
}
}
Usage;
let resizedImage = image.resizedImageWithinRect(rectSize: CGSize(width: 1900, height: 1900))
You have more than one form tags with runat="server" on your template, most probably you have one in your master page, remove one on your aspx page, it is not needed if already have form in master page file which is surrounding your content place holders.
Try to remove that tag:
<form id="formID" runat="server">
and of course closing tag:
</form>
I know I'm late but I found a solution inserting in the head the tag:
<meta http-equiv="X-UA-Compatible" content="IE=edge"/> <!--FIX jQuery INTERNET EXPLORER-->
_x000D_
You can use it like this:
In Mvc:
@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});
In Html:
<input type="text" name="Id" data_val_number="10"/>
---Lalmuni Demos---
create table Users
(
userid int,date_of_birth date
)
---insert values---
insert into Users values(4,'9/10/1991')
select DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years,
MONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months,
DAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,
from users
You can install apps in simulator from Xcode 8.2
From Xcode 8.2,You can install an app (*.app) by dragging any previously built app bundle into the simulator window.
Note: You cannot install apps from the App Store in simulation environments.
Adding a new answer in here because previous answers weren't explaining the issue I had. Problem is that the username required in SQL is the NAME of the app pool, and not its identity.
I ran in IIS with AppPools set to the ApplicationPoolIdentity
identity.
My SQL Security User name with access was called IIS APPPOOL\DefaultAppPool
and it was working fine with a ASP.NET Full Framework .net application.
When launching my ASP.NET Core application, it created a new AppPool with the application name, but no CLR version and still using the same ApplicationPoolIdentity
identity.
But after looking at the user name used via System.Security.Principal.WindowsIdentity.GetCurrent().Name
, I realized it isn't using DefaultAppPool, but the new app pool name. So I had to add a new user called IIS APPPOOL\ApplicationName
in the SQL security tab, and not the default.
Perhaps I am wrong, but you can open a workbook, and select a worksheet and change its property (Name) to whatever you need it to be. This overrides the "Sheetx" naming convention. These names are also displayed in the VBA Editor.
How to do this manually:
1. Select the sheet in a workbook (I tend to create templates).
2. Set its tab name to whatever you like ("foo").
3. Click on the Developer menu (which you previously enabled, right?).
4. Locate "Properties" and click on it, bringing up that worksheet's properties window.
5. The very first item in the Alphabetic listing is (Name) and at the right of (Name) is "Sheetx".
6. Click on that field and change it (how about we use "MyFav").
7. Close the properties window.
8. Go to the Visual Basic editor.
9. Review the sheets in the workbook you just modified.
10. Observe that the MicroSoft Excel Objects shows the name you just changed "MyFav", and to the right of that, in parenthesis, the worksheet tab name ("foo").
You can change the .CodeName programmatically if you would rather. I use non-Sheet names to facilitate my template manipulation. You are not forced to use the generic default of "Sheetx".
This description is very vague. What did you try, and how did it fail.
To include a library with your project, you have to include it in the modules passed to the linker. The exact steps to do this depend on the tools you are using. That part has nothing to do with the OS.
Now, if you are successfully compiling the library into your app and it doesn't run, that COULD be related to the OS.
I think @Deepak answer in this link is more close to correct answer. Max length for client ip address. So correct size is 45 not 39. Sometimes we try to scrounge in fields size but it seems to better if we prepare enough storage size.
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
In VB.Net. Do NOT use "IsNot Nothing" when you can use ".HasValue". I just solved an "Operation could destabilize the runtime" Medium trust error by replacing "IsNot Nothing" with ".HasValue" In one spot. I don't really understand why, but something is happening differently in the compiler. I would assume that "!= null" in C# may have the same issue.
You can convert the int
back to an enumeration member with a simple cast, and then call ToString()
:
int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();
An AsyncTask
is used to do some background computation and publish the result to the UI thread (with optional progress updates). Since you're not concerned with UI, then a Handler
or Thread
seems more appropriate.
You can spawn a background Thread
and pass messages back to your main thread by using the Handler
's post
method.
adb shell getprop ro.build.version.sdk
If you want to see the whole list of parameters just type:
adb shell getprop
I liked Dale's answer, and I also added
git clone --depth 2 --no-checkout repo-to-clone existing-dir/existing-dir.tmp
git branch dev_new214
git checkout dev_new214
git add .
git commit
git checkout dev
git merge dev_new214
The shallow depth avoided a lot of extra early dev commits. The new branch gave us a good visual history that there was some new code from this server that was placed in. That is the perfect use branches in my opinion. My thanks to the great insight of all the people who posted here.
os.walk
does recursive walk by default. For each dir, starting from root it yields a 3-tuple (dirpath, dirnames, filenames)
from os import walk
from os.path import splitext, join
def select_files(root, files):
"""
simple logic here to filter out interesting files
.py files in this example
"""
selected_files = []
for file in files:
#do concatenation here to get full path
full_path = join(root, file)
ext = splitext(file)[1]
if ext == ".py":
selected_files.append(full_path)
return selected_files
def build_recursive_dir_tree(path):
"""
path - where to begin folder scan
"""
selected_files = []
for root, dirs, files in walk(path):
selected_files += select_files(root, files)
return selected_files
As smnbss comments in Darin Dimitrov's answer, Prompt
exists for exactly this purpose, so there is no need to create a custom attribute. From the the documentation:
Gets or sets a value that will be used to set the watermark for prompts in the UI.
To use it, just decorate your view model's property like so:
[Display(Prompt = "numbers only")]
public int Age { get; set; }
This text is then conveniently placed in ModelMetadata.Watermark
. Out of the box, the default template in MVC 3 ignores the Watermark
property, but making it work is really simple. All you need to do is tweaking the default string template, to tell MVC how to render it. Just edit String.cshtml, like Darin does, except that rather than getting the watermark from ModelMetadata.AdditionalValues
, you get it straight from ModelMetadata.Watermark
:
~/Views/Shared/EditorTemplates/String.cshtml:
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", placeholder = ViewData.ModelMetadata.Watermark })
And that is it.
As you can see, the key to make everything work is the placeholder = ViewData.ModelMetadata.Watermark
bit.
If you also want to enable watermarking for multi-line textboxes (textareas), you do the same for MultilineText.cshtml:
~/Views/Shared/EditorTemplates/MultilineText.cshtml:
@Html.TextArea("", ViewData.TemplateInfo.FormattedModelValue.ToString(), 0, 0, new { @class = "text-box multi-line", placeholder = ViewData.ModelMetadata.Watermark })
The question:
Does one unknown equal another unknown?
(NULL = NULL)
That question is something no one can answer so it defaults to true or false depending on your ansi_nulls setting.
However the question:
Is this unknown variable unknown?
This question is quite different and can be answered with true.
nullVariable = null is comparing the values
nullVariable is null is comparing the state of the variable
Update: MixEdit extension now provides this ability.
MultiEdit extension for VS allows for something similar (doesn't support multiple selections as of this writing, just multiple carets)
Head over to Hanselman's for a quick animated gif of this in action: Simultaneous Editing for Visual Studio with the free MultiEdit extension
worked for me:
AVG(CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)
To answer your question, the current method would be to create the object then call the method:
$functions = new Functions();
$var = $functions->filter($_GET['params']);
Another way would be to make the method static
since the class has no private data to rely on:
public static function filter($data){
This can then be called like so:
$var = Functions::filter($_GET['params']);
Lastly, you do not need a class and can just have a file of functions which you include. So you remove the class Functions
and the public
in the method. This can then be called like you tried:
$var = filter($_GET['params']);
I have done good research on the save() vs. persist() including running it on my local machine several times. All the previous explanations are confusing and incorrect. I compare save() and persist() methods below after a thorough research.
Save()
Serializable
;session.save()
for a detached object will create a new row in the table.Persist()
void
;session.persist()
for a detached object will throw a PersistentObjectException
, as it is not allowed.All these are tried/tested on Hibernate v4.0.1
.
Adding to vectran's answer: You also have to set cellspacing
attribute on the table element for cross-browser compatibility.
<table cellspacing="0">
EDIT (for the sake of completeness I'm expanding this 5 years later:):
Internet Explorer 6 and Internet Explorer 7 required you to set cellspacing directly as a table attribute, otherwise the spacing wouldn't vanish.
Internet Explorer 8 and later versions and all other versions of popular browsers - Chrome, Firefox, Opera 4+ - support the CSS property border-spacing.
So in order to make a cross-browser table cell spacing reset (supporting IE6 as a dinosaur browser), you can follow the below code sample:
table{_x000D_
border: 1px solid black;_x000D_
}_x000D_
table td {_x000D_
border: 1px solid black; /* Style just to show the table cell boundaries */_x000D_
}_x000D_
_x000D_
_x000D_
table.no-spacing {_x000D_
border-spacing:0; /* Removes the cell spacing via CSS */_x000D_
border-collapse: collapse; /* Optional - if you don't want to have double border where cells touch */_x000D_
}
_x000D_
<p>Default table:</p>_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>First cell</td>_x000D_
<td>Second cell</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<p>Removed spacing:</p>_x000D_
_x000D_
<table class="no-spacing" cellspacing="0"> <!-- cellspacing 0 to support IE6 and IE7 -->_x000D_
<tr>_x000D_
<td>First cell</td>_x000D_
<td>Second cell</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Is there a single declaration that fixes this for Webkit, Gecko, and Blink? No. However, there is a cross-browser solution by specifying multiple width property values that correspond to each layout engine's convention.
.mydiv {
...
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
...
}
Adapted from: MDN
It's no join since the relationship will only be evaluated when needed. A join (in a SQL database) on the other hand will resolve relationships and return them as if they were a single table (you "join two tables into one").
You can read more about DBRef here: http://docs.mongodb.org/manual/applications/database-references/
There are two possible solutions for resolving references. One is to do it manually, as you have almost described. Just save a document's _id in another document's other_id, then write your own function to resolve the relationship. The other solution is to use DBRefs as described on the manual page above, which will make MongoDB resolve the relationship client-side on demand. Which solution you choose does not matter so much because both methods will resolve the relationship client-side (note that a SQL database resolves joins on the server-side).
For me the most convenient was to: 1) Create directory "bin" in the root of C: drive 2) Add "C:/bin;" to PATH in "My Computer -> Properties -> Environemtal Variables"
Let's keep this simple.
Here is the .cmd file.
@echo off
rem this file is named echo_3params.cmd
echo %1
echo %2
echo %3
set v1=%1
set v2=%2
set v3=%3
echo v1 equals %v1%
echo v2 equals %v2%
echo v3 equals %v3%
Here are 3 calls from the command line.
C:\Users\joeco>echo_3params 1abc 2 def 3 ghi
1abc
2
def
v1 equals 1abc
v2 equals 2
v3 equals def
C:\Users\joeco>echo_3params 1abc "2 def" "3 ghi"
1abc
"2 def"
"3 ghi"
v1 equals 1abc
v2 equals "2 def"
v3 equals "3 ghi"
C:\Users\joeco>echo_3params 1abc '2 def' "3 ghi"
1abc
'2
def'
v1 equals 1abc
v2 equals '2
v3 equals def'
C:\Users\joeco>
A web service, as used by software developers, generally refers to an operation that is performed on a remote server and invoked using the XML/SOAP specification. As with all definitions, there are nuances to it, but that's the most common use of the term.
Sometime it is fixed by the Padding .. if you can play with that, then, it should fix your problem
<style type=text/css>
YourbuttonByID {Padding: 20px 80px; "for example" padding-left:50px;
padding-right:30px "to fix the text in the middle
without interfering with the text itself"}
</style>
It worked for me
To do a border along one side of a select in IE use IE's filters:
select.required { border-left:2px solid red; filter: progid:DXImageTransform.Microsoft.dropshadow(OffX=-2, OffY=0,color=#FF0000) }
I put a border on one side only of all my inputs for required status.
There is probably an effects that do a better job for an all-round border ...
http://msdn.microsoft.com/en-us/library/ms532853(v=VS.85).aspx
From the Microsoft documentation: Command prompt (Cmd. exe) command-line string limitation
On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters.
You can do it with OpenCV's function imwrite
:
import cv2
cv2.imwrite('Path/Image.jpg', image_name)
Compilation from jonearles' answer, http://kishantha.blogspot.com/2010/03/oracle-enterprise-manager-console.html and http://blog.flimatech.com/2011/07/17/changing-oracle-password-in-11g-using-alter-user-identified-by-values/ (Oracle 11g):
To stop this happening in the future do the following.
ALTER PROFILE DEFAULT LIMIT FAILED_LOGIN_ATTEMPTS UNLIMITED PASSWORD_LIFE_TIME UNLIMITED;
To reset users' status, run the query:
select
'alter user ' || su.name || ' identified by values'
|| ' ''' || spare4 || ';' || su.password || ''';'
from sys.user$ su
join dba_users du on ACCOUNT_STATUS like 'EXPIRED%' and su.name = du.username;
and execute some or all of the result set.
I found that some solution didn't work for me in the Simulator within Xcode. Instead, this works:
NSString *deviceModel = (NSString*)[UIDevice currentDevice].model;
if ([[deviceModel substringWithRange:NSMakeRange(0, 4)] isEqualToString:@"iPad"]) {
DebugLog(@"iPad");
} else {
DebugLog(@"iPhone or iPod Touch");
}
if UIDevice.current.model.hasPrefix("iPad") {
print("iPad")
} else {
print("iPhone or iPod Touch")
}
Also in the 'Other Examples' in Xcode the device model comes back as 'iPad Simulator' so the above tweak should sort that out.
I have the same problem and fix by add "new." before the field is updated. And I post full trigger here for someone to want to write a trigger
DELIMITER $$
USE `nc`$$
CREATE
TRIGGER `nhachung_province_count_update` BEFORE UPDATE ON `nhachung`
FOR EACH ROW BEGIN
DECLARE slug_province VARCHAR(128);
DECLARE slug_district VARCHAR(128);
IF old.status!=new.status THEN /* neu doi status */
IF new.status="Y" THEN
UPDATE province SET `count`=`count`+1 WHERE id = new.district_id;
ELSE
UPDATE province SET `count`=`count`-1 WHERE id = new.district_id;
END IF;
ELSEIF old.province_id!=new.province_id THEN /* neu doi province_id + district_id */
UPDATE province SET `count`=`count`+1 WHERE id = new.province_id; /* province_id */
UPDATE province SET `count`=`count`-1 WHERE id = old.province_id;
UPDATE province SET `count`=`count`+1 WHERE id = new.district_id; /* district_id */
UPDATE province SET `count`=`count`-1 WHERE id = old.district_id;
SET slug_province = ( SELECT slug FROM province WHERE id= new.province_id LIMIT 0,1 );
SET slug_district = ( SELECT slug FROM province WHERE id= new.district_id LIMIT 0,1 );
SET new.prov_dist_url=CONCAT(slug_province, "/", slug_district);
ELSEIF old.district_id!=new.district_id THEN
UPDATE province SET `count`=`count`+1 WHERE id = new.district_id;
UPDATE province SET `count`=`count`-1 WHERE id = old.district_id;
SET slug_province = ( SELECT slug FROM province WHERE id= new.province_id LIMIT 0,1 );
SET slug_district = ( SELECT slug FROM province WHERE id= new.district_id LIMIT 0,1 );
SET new.prov_dist_url=CONCAT(slug_province, "/", slug_district);
END IF;
END;
$$
DELIMITER ;
Hope this help someone
In my case, the site was fine in server but not in local. Then I remember I was working on secure website.
So in file config.session.php, set the variable secure to false
'secure' => env('SESSION_SECURE_COOKIE', false),
Just use -p1
: you will need to use -p0
in the --no-prefix
case anyway, so you can just leave out the --no-prefix
and use -p1
:
$ git diff > save.patch
$ patch -p1 < save.patch
$ git diff --no-prefix > save.patch
$ patch -p0 < save.patch
I wrote this script for switching DNS servers of all currently enabled interfaces to specific address:
@echo off
:: Google DNS
set DNS1=8.8.8.8
set DNS2=8.8.4.4
for /f "tokens=1,2,3*" %%i in ('netsh int show interface') do (
if %%i equ Enabled (
echo Changing "%%l" : %DNS1% + %DNS2%
netsh int ipv4 set dns name="%%l" static %DNS1% primary validate=no
netsh int ipv4 add dns name="%%l" %DNS2% index=2 validate=no
)
)
ipconfig /flushdns
:EOF
This will display the selected values:
<?php
if ($_POST) {
foreach($_POST['select2'] as $selected) {
echo $selected."<br>";
}
}
?>
You can use Apache Subversion. It is owner of subversion . You can download from here . After install it, you have to restart pc to use svn from command line.
If you are using Underscore JS, just use :
var result = _.chunk(arr,elements_per_chunk)
Most projects already use underscore as a dependency, anyways.
I ran into the same problem today. And here is how I managed to run python code in Sublime Text 3:
What you need to do next is replace the content in Python.sublime-build
to
{
"cmd": ["/usr/local/bin/python", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
}
You can of course further customise it to something that works for you.
A panel expands to a span (or a div), with it's content within it. A placeholder is just that, a placeholder that's replaced by whatever you put in it.
This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.
It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.
The relevant section is:
select *
from
( select *
from emp
order by sal desc )
where ROWNUM <= 5;
You can also run docker build with -f
option
docker build -t ubuntu-test:latest -f Dockerfile.custom .
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
You can also use the Pivot Keyword if you are using SQL 2005 or above
SELECT *
FROM @Users
PIVOT (
COUNT(Position)
FOR Position
IN (Manager, CEO, Employee)
) as p
Test Data Set
DECLARE @Users TABLE (Position VARCHAR(10))
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('CEO')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
I wrote a small gist which I think can be very helpful to anybody seeking a solution to that problem: external link
What it does is it adds target="_blank"
attributes to anchor elements that would link to a domain different than the current one.
You can patch it up to whatever you see fit.
The value
attribute on submit
-type <input>
elements controls the text displayed.
<input type="submit" class="like" value="Like" />
view.layer.cornerRadius = 25
view.layer.masksToBounds = true
There are two main ways that you can do this. One of them is the standard CakePHP way, and the other is using a custom join.
It's worth pointing out that this advice is for CakePHP 2.x, not 3.x.
You would create a relationship with your User model and Messages Model, and use the containable behavior:
class User extends AppModel {
public $actsAs = array('Containable');
public $hasMany = array('Message');
}
class Message extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array('User');
}
You need to change the messages.from
column to be messages.user_id
so that cake can automagically associate the records for you.
Then you can do this from the messages controller:
$this->Message->find('all', array(
'contain' => array('User')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
I recommend using the first method, because it will save you a lot of time and work. The first method also does the groundwork of setting up a relationship which can be used for any number of other find calls and conditions besides the one you need now. However, cakePHP does support a syntax for defining your own joins. It would be done like this, from the MessagesController
:
$this->Message->find('all', array(
'joins' => array(
array(
'table' => 'users',
'alias' => 'UserJoin',
'type' => 'INNER',
'conditions' => array(
'UserJoin.id = Message.from'
)
)
),
'conditions' => array(
'Message.to' => 4
),
'fields' => array('UserJoin.*', 'Message.*'),
'order' => 'Message.datetime DESC'
));
Note, I've left the field name messages.from
the same as your current table in this example.
Here is how you can do the first example using two relationships to the same model:
class User extends AppModel {
public $actsAs = array('Containable');
public $hasMany = array(
'MessagesSent' => array(
'className' => 'Message',
'foreignKey' => 'from'
)
);
public $belongsTo = array(
'MessagesReceived' => array(
'className' => 'Message',
'foreignKey' => 'to'
)
);
}
class Message extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array(
'UserFrom' => array(
'className' => 'User',
'foreignKey' => 'from'
)
);
public $hasMany = array(
'UserTo' => array(
'className' => 'User',
'foreignKey' => 'to'
)
);
}
Now you can do your find call like this:
$this->Message->find('all', array(
'contain' => array('UserFrom')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);
Does your script reference /bin/bash
or /bin/sh
in its hash bang line? The default system shell in Ubuntu is dash, not bash, so if you have #!/bin/sh
then your script will be using a different shell than you expect. Dash does not have the <<<
redirection operator.
You can use this to continue using the type Date and a more legible code, if you preffer:
import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);
See this article on SQL Server Helper - SQL Server 2008 Date Format
Try
System.exit(0);
this should terminate thread main and end the main program
On Windows (with Windows Service).
Edit the file C:\Program Files (x86)\Jenkins\jenkins.xml
with 8083 if you want 8083 port.
<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8083</arguments>
This should do it:
SELECT *
FROM INFORMATION_SCHEMA.VIEWS
WHERE VIEW_DEFINITION like '%YourTableName%'
this bellow code gave me correct response
jar cvf MyJar.jar *.properties lib/*.jar -C bin .
it added the (log4j) properties file, it added the jar files in lib. and then it went inside bin to retrieve the class files with package.
I am using remove and replace both for refreshing content of Fragment like
final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.remove(resetFragment).commit();
fragmentTransaction.replace(R.id.frame_container,resetFragment).commit();
To my knowledge there is no cross-browser compatible way to make a circle with CSS & HTML only.
For the square I guess you could make a div with a border and a z-index higher than what you are putting it over. I don't understand why you would need to do this, when you could just put a border on the image or "something" itself.
If anyone else knows how to make a circle that is cross browser compatible with CSS & HTML only, I would love to hear about it!
@Caspar Kleijne border-radius does not work in IE8 or below, not sure about 9.
Had problems even when init.py existed in subfolder and all that was missing was adding 'as' after import
from folder.file import Class as Class
import folder.file as functions
It could be something like that:
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var arrays = [], size = 3;
while (a.length > 0)
arrays.push(a.splice(0, size));
console.log(arrays);
_x000D_
See splice Array's method.