private String encodeFileToBase64Binary(File file){
String encodedfile = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
encodedfile = Base64.encodeBase64(bytes).toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedfile;
}
You normally end a batch file with a line that just says exit
. If you want to make sure the file has run and the DOS window closes after 2 seconds, you can add the lines:
timeout 2 >nul
exit
But the exit
command will not work if your batch file opens another window, because while ever the second window is open the old DOS window will also be displayed.
SOLUTION: For example there's a great little free program called BgInfo which will display all the info about your computer. Assuming it's in a directory called C:\BgInfo
, to run it from a batch file with the /popup
switch and to close the DOS window while it still runs, use:
start "" "C:\BgInfo\BgInfo.exe" /popup
exit
Path: Android Studio Preference / Build, Execution, Deployment / Instant Run
Go to Android Studio Preference (for Mac) or Settings (for windows)
Choose Build, Execution, Deployment tab
Choose Instant Run
Uncheck Enable Instant Run to hot swap code/resources changes on deply (default enabled)
It works for me!!
The following example demonstrates how to encrypt and decrypt sample data:
// This constant is used to determine the keysize of the encryption algorithm in bits.
// We divide this by 8 within the code below to get the equivalent number of bytes.
private const int Keysize = 128;
// This constant determines the number of iterations for the password bytes generation function.
private const int DerivationIterations = 1000;
public static string Encrypt(string plainText, string passPhrase)
{
// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
var saltStringBytes = GenerateBitsOfRandomEntropy(16);
var ivStringBytes = GenerateBitsOfRandomEntropy(16);
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
var cipherTextBytes = saltStringBytes;
cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
}
public static string Decrypt(string cipherText, string passPhrase)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
}
}
}
private static byte[] GenerateBitsOfRandomEntropy(int size)
{
// 32 Bytes will give us 256 bits.
// 16 Bytes will give us 128 bits.
var randomBytes = new byte[size];
using (var rngCsp = new RNGCryptoServiceProvider())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
If you need to separate certain elements with spaces you could do something like
print "hello", "there"
Notice the comma between "hello" and "there".
If you want to print a new line (i.e. \n
) you could just use print
without any arguments.
You can give your input textboxes class names, like so:
<input type="text" value="2" name="pages_title[1]" class="pages_title">
<input type="text" value="1" name="pages_title[2]" class="pages_title">
and iterate like so:
$('input.pages_title').each(function() {
alert($(this).val());
});
Give unique class and different id for file input
$("#tab-content").on('change',class,function()
{
var id=$(this).attr('id');
$("#"+id).trigger(your function);
//for name of file input $("#"+id).attr("name");
});
You should create the response using Request.CreateResponse:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error message");
You can pass objects not just strings to CreateResponse and it will serialize them based on the request's Accept header. This saves you from manually choosing a formatter.
From answer that was removed due to being written in Spanish:
All of the above fixes may not work in android studio. If you are using ANDROID STUDIO please use the following fix.
Use
xmlns: compat = "http://schemas.android.com/tools"
on the menu label instead of
xmlns: compat = "http://schemas.android.com/apk/res-auto"
use onPause()
method to do what you want to do on home button.
Use CSS's :disabled
selector (for CSS3):
checkbox-style { }
checkbox-style:disabled { }
Or you need to use javascript to alter the style based on when you enable/disable it (Assuming it is being enabled/disabled based on your question).
Also, if you want to send embedded spaces with the input command, use %s
adb shell input text 'this%sis%san%sexample'
will yield
this is an example
being input.
%
itself does not need escaping - only the special %s
pair is treated specially. This leads of course to the obvious question of how to enter the literal string %s
, which you would have to do with two separate commands.
Running powershell scripts on linux from bash gives the same problem. Solved it almost the same as LarsWA's answer:
Working:
pwsh -f ./test.ps1 -bool:true
Not working:
pwsh -f ./test.ps1 -bool=1
pwsh -f ./test.ps1 -bool=true
pwsh -f ./test.ps1 -bool true
pwsh -f ./test.ps1 {-bool=true}
pwsh -f ./test.ps1 -bool=$true
pwsh -f ./test.ps1 -bool=\$true
pwsh -f ./test.ps1 -bool 1
pwsh -f ./test.ps1 -bool:1
Try this:
public class Team
{
public int TeamId { get; set;}
public string Name { get; set; }
public virtual ICollection<Match> HomeMatches { get; set; }
public virtual ICollection<Match> AwayMatches { get; set; }
}
public class Match
{
public int MatchId { get; set; }
public int HomeTeamId { get; set; }
public int GuestTeamId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
public class Context : DbContext
{
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Match>()
.HasRequired(m => m.HomeTeam)
.WithMany(t => t.HomeMatches)
.HasForeignKey(m => m.HomeTeamId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Match>()
.HasRequired(m => m.GuestTeam)
.WithMany(t => t.AwayMatches)
.HasForeignKey(m => m.GuestTeamId)
.WillCascadeOnDelete(false);
}
}
Primary keys are mapped by default convention. Team must have two collection of matches. You can't have single collection referenced by two FKs. Match is mapped without cascading delete because it doesn't work in these self referencing many-to-many.
Like any project setting, the buildevents can be configured per Configuration. Just select the configuration you want to change in the dropdown of the Property Pages dialog and edit the post build step.
Go to Applications > Xcode > preferences > downloads
You should see the command line tools there for you to install.
If you do not want to rely on the 3.5 kB plugin for jQuery or do not want to construct the HTML string while escapping reserved HTML characters, here is a simple way that works:
function addOptionToSelectBox(selectBox, optionId, optionText, selectIt)
{
var option = document.createElement("option");
option.value = optionId;
option.text = optionText;
selectBox.options[selectBox.options.length] = option;
if (selectIt) {
option.selected = true;
}
}
var selectBox = $('#veryImportantSelectBox')[0];
addOptionToSelectBox(selectBox, "ID1", "Option 1", true);
try this
$(document).on("submit", "#form-data", function(e){
e.preventDefault()
$.ajax({
url: "edit.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data){
$('.center').html(data);
}
})
})
in the form the button needs to be type="submit"
You can't make window.open
modal and I strongly recommend you not to go that way.
Instead you can use something like jQuery UI's dialog widget.
UPDATE:
You can use load()
method:
$("#dialog").load("resource.php").dialog({options});
This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.
And you can use an IFRAME:
$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});
This is slower, but will submit independently.
For linux you can install it via
sudo apt-get install php5-curl
For Windows(removing the ;) from php.ini
;extension=php_curl.dll
Restart apache server.
Not orthodox, but it works for me sometimes; set your comment as another attribute:
<node usefulAttr="foo" comment="Your comment here..."/>
YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...
you could change the innerHtml on an element
function produceMessage(){
var msg= 'Hello<br />';
document.getElementById('someElement').innerHTML = msg;
}
Apply float:left;
to both of your divs should make them stand side by side.
Read the Request.Form NameValueCollection and process your logic accordingly:
NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}
if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}
//Process login
CheckLogin(userName, password);
... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.
Yet another alternative if you have a controller just specific to that page:
(function(){
//code to run
}());
In my case this error appeared when I asigned to both dynamic created controls (combobox), same created control from other class.
//dynamic created controls
ComboBox combobox1 = ManagerControls.myCombobox1;
...some events
ComboBox combobox2 = ManagerControl.myComboBox2;
...some events
.
//method in constructor
public static void InitializeDynamicControls()
{
ComboBox cb = new ComboBox();
cb.Background = new SolidColorBrush(Colors.Blue);
...
cb.Width = 100;
cb.Text = "Select window";
ManagerControls.myCombobox1 = cb;
ManagerControls.myComboBox2 = cb; // <-- error here
}
Solution: create another ComboBox cb2
and assign it to ManagerControls.myComboBox2
.
I hope I helped someone.
GridView.Columns.Count
will always be 0 when your GridView has its AutoGenerateColumns
property set to true
(default is true
).
You can explicitly declare your columns and set the AutoGenerateColumns
property to false
, or you can use this in your codebehind:
GridView.Rows[0].Cells.Count
to get the column count once your GridView data has been bound, or this:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[index].Visible = false;
}
to set a column invisible using your GridView's RowDataBound
event.
Firstly, if you don't want the user to modify the data, then it seems cleaner to simply exclude the field. Including it as a hidden field just adds more data to send over the wire and invites a malicious user to modify it when you don't want them to. If you do have a good reason to include the field but hide it, you can pass a keyword arg to the modelform's constructor. Something like this perhaps:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
from django.forms.widgets import HiddenInput
hide_condition = kwargs.pop('hide_condition',None)
super(MyModelForm, self).__init__(*args, **kwargs)
if hide_condition:
self.fields['fieldname'].widget = HiddenInput()
# or alternately: del self.fields['fieldname'] to remove it from the form altogether.
Then in your view:
form = MyModelForm(hide_condition=True)
I prefer this approach to modifying the modelform's internals in the view, but it's a matter of taste.
If you're writing Python using Sublime and getting indentation errors,
view -> indentation -> convert indentation to spaces
The issue I'm describing is caused by the Sublime text editor. The same issue could be caused by other editors as well. Essentially, the issue has to do with Python wanting to treat indentations in terms of spaces versus various editors coding the indentations in terms of tabs.
I'm currently in the process of building a single page application. Here is what I have thus far that I believe would be answering your question. I have a base template (base.html) that has a div with the ng-view
directive in it. This directive tells angular where to put the new content in. Note that I'm new to angularjs myself so I by no means am saying this is the best way to do it.
app = angular.module('myApp', []);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/home/', {
templateUrl: "templates/home.html",
controller:'homeController',
})
.when('/about/', {
templateUrl: "templates/about.html",
controller: 'aboutController',
})
.otherwise({
template: 'does not exists'
});
});
app.controller('homeController', [
'$scope',
function homeController($scope,) {
$scope.message = 'HOME PAGE';
}
]);
app.controller('aboutController', [
'$scope',
function aboutController($scope) {
$scope.about = 'WE LOVE CODE';
}
]);
base.html
<html>
<body>
<div id="sideMenu">
<!-- MENU CONTENT -->
</div>
<div id="content" ng-view="">
<!-- Angular view would show here -->
</div>
<body>
</html>
i wrote a small function.. but works for me
def conv(strng):
k=strng
k=k.replace('\a','\\a')
k=k.replace('\b','\\b')
k=k.replace('\f','\\f')
k=k.replace('\n','\\n')
k=k.replace('\r','\\r')
k=k.replace('\t','\\t')
k=k.replace('\v','\\v')
return k
do i need to configure proxy settings? because my office has got proxy servers.
Yes, you can do so by setting HTTP_PROXY
, and HTTPS_PROXY
environment variables.
See "Syncing with github":
set HTTPS_PROXY=http://<login_internet>:<password_internet>@aproxy:aport
set HTTP_PROXY=http://<login_internet>:<password_internet>@aproxy:aport
set NO_PROXY=localhost,my.company
(To avoid putting your credentials -- username/password -- in clear in the proxy URL, see below)
Note the NO_PROXY
, to allow to access internal site to your company
You also can register that in your git config:
git config --global http.proxy http://<login_internet>:<password_internet>@aproxy:aport
But if you have incorrect proxy Git settings, remove them:
cd /path/to/repo
git config --unset http.proxy
git config --global --unset http.proxy
git config --system --unset http.proxy
git config --unset https.proxy
git config --global --unset https.proxy
git config --system --unset https.proxy
# double-check with:
git config -l --show-origin | grep -i proxy
No credentials needed: use genotrance/px
.
If you are, as I am, in a company behind a NTLM proxy, all you need to do is:
px-v0.4.0.zip
anywhere you wantpx.ini
config file (put it in %USERPROFILE%
), chaging the server
line:
[proxy]
server = proxy.my.company:8080 <= use your company proxy:port
listen = 127.0.0.1
port = 3128
px
proxy will reuse the ones from the current Widows session, either through Microsoft SSPI or Microsoft Kerberos)That will give you:
set HTTPS_PROXY=http://127.0.0.1:3128
set HTTP_PROXY=http://127.0.0.1:3128
set NO_PROXY=localhost,my.company
When I look at this description, I have a feeling, that this xdr integer is just a big-endian "standard" integer, but it's expressed in the most obfuscated way. Two's complement notation is better know as U2, and it's what we are using on today's processors. The byte order indicates that it's a big-endian notation.
So, answering your question, you should inverse elements in your array (0 <--> 3, 1 <-->2), as they are encoded in little-endian. Just to make sure, you should first check BitConverter.IsLittleEndian
to see on what machine you are running.
Personally I sanitize all my data with some PHP libraries before going into the database so there's no need for another XSS filter for me.
From AngularJS 1.0.8
directives.directive('ngBindHtmlUnsafe', [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
}
}]);
To use:
<div ng-bind-html-unsafe="group.description"></div>
To disable $sce
:
app.config(['$sceProvider', function($sceProvider) {
$sceProvider.enabled(false);
}]);
An example,
d <- data.frame(x1=rnorm(10),
x2=rnorm(10),
x3=rnorm(10))
cor(d) # get correlations (returns matrix)
You can simply use
<a href="directry/filename.html#section5" >click me</a>
to link to a section/id of another page by
Pandas uses numpy
's NaN value. Use numpy.isnan
to obtain a Boolean vector from a pandas series.
A view uses a query to pull data from the underlying tables.
A materialized view is a table on disk that contains the result set of a query.
Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH
option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH
has been in place since at least Oracle 10.
I think the problem may be that you are not finding your element because of the "#" in your call to get it:
window.parent.document.getElementById('#target');
You only need the # if you are using jquery. Here it should be:
window.parent.document.getElementById('target');
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.
If you are using other version control software, it may be in conflict. In my case, uninstalling Plastic SCM restored Tortoise SVN icons.
I was having problem in Windows 7 with PHP 5.4.0 in command line, using Xampp 1.8.1 server. This is what i did:
php.ini-production
to php.ini
(in C:\xampp\php\ folder)php.ini
and uncomment extension_dir=ext
.extension=php_openssl.dll
.After that it worked fine.
I was looking for a way to change the script and debug that new script. Way I managed to do that is:
Set the breakpoint in the first line of the script you want to change and debug.
Reload the page so the breakpoint is being hit
Paste your new script and set desired breakpoints in it
Ctrl+s, and the page will refresh causing that breakpoint in first line to be hit.
F8 to continue, and now your newly pasted script replaces original one as long as no redirections and reloads are made.
If you have MAMP PRO you can set up a host like mysite.local, then add some options from the 'Advanced' panel in the main window. Just switch on the options 'Indexes' and 'MultiViews'. 'Includes' and 'FollowSymLinks' should already be checked.
If you want to convert from char to int, why not think about unicode number?
SELECT UNICODE(';') -- 59
This way you can convert any char to int without any error. Cheers.
By using the following code you can find name, path, size as like this all kind of information of all audio song files
String[] STAR = { "*" };
Uri allaudiosong = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String audioselection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor;
cursor = managedQuery(allaudiosong, STAR, audioselection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
System.out.println("Audio Song Name= "+song_name);
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
System.out.println("Audio Song ID= "+song_id);
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
System.out.println("Audio Song FullPath= "+fullpath);
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
System.out.println("Audio Album Name= "+album_name);
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
System.out.println("Audio Album Id= "+album_id);
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
System.out.println("Audio Artist Name= "+artist_name);
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("Audio Artist ID= "+artist_id);
} while (cursor.moveToNext());
yes, there is:
object[] x = new object[2];
x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };
you were practically there, just the declaration of the anonymous types was a little off.
Here, using your notation:
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
data[propName] = 'Some New Property value'
The practical difference is binding strength, which can lead to peculiar behavior if you're not prepared for it:
foo = :foo
bar = nil
a = foo and bar
# => nil
a
# => :foo
a = foo && bar
# => nil
a
# => nil
a = (foo and bar)
# => nil
a
# => nil
(a = foo) && bar
# => nil
a
# => :foo
The same thing works for ||
and or
.
You can use this variation:
import pandas as pd
vals = {
'name' : ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
'gender' : ['m', 'f', 'f', 'f', 'f', 'c', 'c'],
'age' : [39, 12, 27, 13, 36, 29, 10],
'education' : ['ma', None, 'school', None, 'ba', None, None]
}
df_vals = pd.DataFrame(vals) #converting dict to dataframe
This will output(** - highlighting only desired rows):
age education gender name
0 39 ma m n1 **
1 12 None f n2
2 27 school f n3 **
3 13 None f n4
4 36 ba f n5 **
5 29 None c n6
6 10 None c n7
So to drop everything that does not have an 'education' value, use the code below:
df_vals = df_vals[~df_vals['education'].isnull()]
('~' indicating NOT)
Result:
age education gender name
0 39 ma m n1
2 27 school f n3
4 36 ba f n5
I think a 32 bit JVM has a maximum of 2GB memory.This might be out of date though. If I understood correctly, you set the -Xmx on Eclipse launcher. If you want to increase the memory for the program you run from Eclipse, you should define -Xmx in the "Run->Run configurations..."(select your class and open the Arguments tab put it in the VM arguments area) menu, and NOT on Eclipse startup
Edit: details you asked for. in Eclipse 3.4
Run->Run Configurations...
if your class is not listed in the list on the left in the "Java Application" subtree, click on "New Launch configuration" in the upper left corner
on the right, "Main" tab make sure the project and the class are the right ones
select the "Arguments" tab on the right.
this one has two text areas. one is for the program arguments that get in to the args[] array supplied to your main method. the other one is for the VM arguments. put into the one with the VM arguments(lower one iirc) the following:
-Xmx2048m
I think that 1024m should more than enough for what you need though!
Click Apply, then Click Run
Should work :)
m(new String[]{"blah", "hey", "yo"});
try with this code...
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>/social.properties</value>
</list>
</property>
</bean>
For me this message:
org.apache.wicket.WicketRuntimeException: Can't instantiate page using constructor 'public org.package.MyClass(org.apache.wicket.request.mapper.parameter.PageParameters)' and argument ''. Might be it doesn't exist, may be it is not visible (public).
meant "in my wicket unit test at the top you have to manually add that bean in like"
appContext.putBean(myClass);
I encountered a similar problem when I was using the below to obtain connection factory
ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");
Its resolved when I changed it to the below
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");
The below then showed that my Q size was increasing..
http://:8161/admin/queues.jsp
.h
files will nothing to do with compiling ... you only care about cpp files... so type g++ filename1.cpp filename2.cpp main.cpp -o myprogram
means you are compiling each cpp files and then linked them together into myprgram
.
then run your program ./myprogram
Perhaps you can try to BeginInvoke a delegate pointing to your method like so:
delegate string SynchOperation(string value);
class Program
{
static void Main(string[] args)
{
BeginTheSynchronousOperation(CallbackOperation, "my value");
Console.ReadLine();
}
static void BeginTheSynchronousOperation(AsyncCallback callback, string value)
{
SynchOperation op = new SynchOperation(SynchronousOperation);
op.BeginInvoke(value, callback, op);
}
static string SynchronousOperation(string value)
{
Thread.Sleep(10000);
return value;
}
static void CallbackOperation(IAsyncResult result)
{
// get your delegate
var ar = result.AsyncState as SynchOperation;
// end invoke and get value
var returned = ar.EndInvoke(result);
Console.WriteLine(returned);
}
}
Then use the value in the method you sent as AsyncCallback to continue..
new File(path).toURI().toURL();
I also had the same problem. I use "Postman" for JSON request. The code itself is not wrong. I simply set the content type to JSON (application/json
) and it worked, as you can see on the image below
You can define your title programatically using setTitle
within your Activity
, this method can accept either a String
or an ID defined in your values/strings.xml
file. Example:
public class YourActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
setTitle(R.string.your_title);
setContentView(R.layout.main);
}
}
The offending lines are the following:
MaxConnections=90
InitialConnections=80
You can increase the values to allow more connections.
I had the same problem and after reading this topic, I've solved adding this to my CSS:
.navbar-fixed-top {
z-index: 10000;
}
because in my case, I'm using the fixed top menu.
You can either Drop the columns you do not need OR Select the ones you need
# Using DataFrame.drop
df.drop(df.columns[[1, 2]], axis=1, inplace=True)
# drop by Name
df1 = df1.drop(['B', 'C'], axis=1)
# Select the ones you want
df1 = df[['a','d']]
Here's the version with one stack and without a visited flag:
private void postorder(Node head) {
if (head == null) {
return;
}
LinkedList<Node> stack = new LinkedList<Node>();
stack.push(head);
while (!stack.isEmpty()) {
Node next = stack.peek();
boolean finishedSubtrees = (next.right == head || next.left == head);
boolean isLeaf = (next.left == null && next.right == null);
if (finishedSubtrees || isLeaf) {
stack.pop();
System.out.println(next.value);
head = next;
}
else {
if (next.right != null) {
stack.push(next.right);
}
if (next.left != null) {
stack.push(next.left);
}
}
}
}
I have this issue whenever I run a Perl script, such as enum4linux, on the latest Kali Linux version.
kali@kali:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Kali
Description: Kali GNU/Linux Rolling
Release: 2020.3
Codename: kali-rolling
kali@kali:~$
E.g.,
kali@kali:~$ enum4linux
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = (unset),
LC_ALL = (unset),
LC_ADDRESS = "ms_MY.UTF-8",
LC_NAME = "ms_MY.UTF-8",
LC_MONETARY = "ms_MY.UTF-8",
LC_PAPER = "ms_MY.UTF-8",
LC_IDENTIFICATION = "ms_MY.UTF-8",
LC_TELEPHONE = "ms_MY.UTF-8",
LC_MEASUREMENT = "ms_MY.UTF-8",
LC_TIME = "ms_MY.UTF-8",
LC_NUMERIC = "ms_MY.UTF-8",
LANG = "en_US.UTF-8"
are supported and installed on your system.
perl: warning: Falling back to a fallback locale ("en_US.UTF-8").
enum4linux v0.8.9 (http://labs.portcullis.co.uk/application/enum4linux/)
Copyright (C) 2011 Mark Lowe ([email protected])
Look at the warning message given.
perl: warning: Falling back to a fallback locale ("en_US.UTF-8").
Also, notice that LC_ALL = (unset)
The solution is simple. All you have to do is to set it.
export LC_ALL=en_US.UTF-8
E.g.,
kali@kali:~$ export LC_ALL=en_US.UTF-8
kali@kali:~$
And problem solved
kali@kali:~$ enum4linux
enum4linux v0.8.9 (http://labs.portcullis.co.uk/application/enum4linux/)
Copyright (C) 2011 Mark Lowe ([email protected])
For a permanent solution, you might want to add it to the .bashrc
file.
Try this:
int getYear(Date date1,Date date2){
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy");
Integer.parseInt(simpleDateformat.format(date1));
return Integer.parseInt(simpleDateformat.format(date2))- Integer.parseInt(simpleDateformat.format(date1));
}
SWIFT 2
I was able to successfully change the appearance of the status bar background by adding the following in my viewWillAppear:
let statusBar: UIView = UIApplication.sharedApplication().valueForKey("statusBar") as! UIView
if statusBar.respondsToSelector(Selector("setBackgroundColor:")) {
statusBar.backgroundColor = .redColor()
}
In my opinion, extension methods are the most comfortable way to solve this.
I took Steve in CO's excellent answer and put it into an extension class as follows, together with a second method I added to support the other direction (string -> secure string) as well, so you can create a secure string and convert it into a normal string afterwards:
public static class Extensions
{
// convert a secure string into a normal plain text string
public static String ToPlainString(this System.Security.SecureString secureStr)
{
String plainStr=new System.Net.NetworkCredential(string.Empty, secureStr).Password;
return plainStr;
}
// convert a plain text string into a secure string
public static System.Security.SecureString ToSecureString(this String plainStr)
{
var secStr = new System.Security.SecureString(); secStr.Clear();
foreach (char c in plainStr.ToCharArray())
{
secStr.AppendChar(c);
}
return secStr;
}
}
With this, you can now simply convert your strings back and forth like so:
// create a secure string
System.Security.SecureString securePassword = "MyCleverPwd123".ToSecureString();
// convert it back to plain text
String plainPassword = securePassword.ToPlainString(); // convert back to normal string
But keep in mind the decoding method should only be used for testing.
i was trying to use airbnb deeplink dispatch and got this error. i had to also exlude the findbugs group from the annotationProcessor.
//airBnb
compile ('com.airbnb:deeplinkdispatch:3.1.1'){
exclude group:'com.google.code.findbugs'
}
annotationProcessor ('com.airbnb:deeplinkdispatch-processor:3.1.1'){
exclude group:'com.google.code.findbugs'
}
What is the error you're getting?
$ bash file.sh
test.sh: line 8: syntax error: unexpected end of file
If you get that error, you may have bad line endings. Unix uses <LF>
at the end of the file while Windows uses <CR><LF>
. That <CR>
character gets interpreted as a character.
You can use od -a test.sh
to see the invisible characters in the file.
$ od -a test.sh
0000000 # ! / b i n / b a s h cr nl # sp cr
0000020 nl w h i l e sp : cr nl d o cr nl sp sp
0000040 sp sp e c h o sp " P r e s s sp [ C
0000060 T R L + C ] sp t o sp s t o p " cr
0000100 nl sp sp sp sp s l e e p sp 1 cr nl d o
0000120 n e cr nl
0000124
The sp
stands for space, the ht
stands for tab, the cr
stands for <CR>
and the nl
stands for <LF>
. Note that all of the lines end with cr
followed by a nl
character.
You can also use cat -v test.sh
if your cat
command takes the -v
parameter.
If you have dos2unix
on your box, you can use that command to fix your file:
$ dos2unix test.sh
The problem with your code is that you are selecting the .remode_hover
that is a descendant of .remode_selected
. So the first part of getting your code to work correctly is by removing that space
.reMode_selected.reMode_hover:hover
Then, in order to get the style to not work, you have to override the style set by the :hover
. In other words, you need to counter the background-color
property. So the final code will be
.reMode_selected.reMode_hover:hover {
background-color:inherit;
}
.reMode_hover:hover {
background-color: #f0ac00;
}
An alternative method would be to use :not()
, as stated by others. This will return any element that doesn't have the class or property stated inside the parenthesis. In this case, you would put .remode_selected
in there. This will target all elements that don't have a class of .remode_selected
However, I would not recommend this method, because of the fact that it was introduced in CSS3, so browser support is not ideal.
A third method would be to use jQuery. You can target the .not()
selector, which would be similar to using :not()
in CSS, but with much better browser support
You can do this easily manually for each column like this:
df['A_perc'] = df['A']/df['sum']
If you want to do this in one step for all columns, you can use the div
method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):
ds.div(ds['sum'], axis=0)
And if you want this in one step added to the same dataframe:
>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
A B C D sum A_perc B_perc \
1 0.151722 0.935917 1.033526 0.941962 3.063127 0.049532 0.305543
2 0.033761 1.087302 1.110695 1.401260 3.633017 0.009293 0.299283
3 0.761368 0.484268 0.026837 1.276130 2.548603 0.298739 0.190013
C_perc D_perc sum_perc
1 0.337409 0.307517 1
2 0.305722 0.385701 1
3 0.010530 0.500718 1
All strings meant for humans should use u"".
I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u""
syntax. The ""
syntax is for byte arrays, only.
Before the bashing begins, let me explain. Most Python programs start out with using ""
for strings. But then they need to support documentation off the Internet, so they start using "".decode
and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of ""
for strings. In this case, Unicode does act like a virus and will wreak havoc.
But, if you follow my rule, you won't have this infection (because you will already be infected).
JavaScript:
function maketimus(timestampz)
{
var linktime = new Date(timestampz * 1000);
var linkday = linktime.getDate();
var freakingmonths = new Array();
freakingmonths[0] = "jan";
freakingmonths[1] = "feb";
freakingmonths[2] = "mar";
freakingmonths[3] = "apr";
freakingmonths[4] = "may";
freakingmonths[5] = "jun";
freakingmonths[6] = "jul";
freakingmonths[7] = "aug";
freakingmonths[8] = "sep";
freakingmonths[9] = "oct";
freakingmonths[10] = "nov";
freakingmonths[11] = "dec";
var linkmonthnum = linktime.getMonth();
var linkmonth = freakingmonths[linkmonthnum];
var linkyear = linktime.getFullYear();
var linkhour = linktime.getHours();
var linkminute = linktime.getMinutes();
if (linkminute < 10)
{
linkminute = "0" + linkminute;
}
var fomratedtime = linkday + linkmonth + linkyear + " " +
linkhour + ":" + linkminute + "h";
return fomratedtime;
}
Simply provide your times in Unix timestamp format to this function; JavaScript already knows the timezone of the user.
Like this:
PHP:
echo '<script type="text/javascript">
var eltimio = maketimus('.$unix_timestamp_ofshiz.');
document.write(eltimio);
</script><noscript>pls enable javascript</noscript>';
This will always show the times correctly based on the timezone the person has set on his/her computer clock. There is no need to ask anything to anyone and save it into places, thank god!
Use this annotation
@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})
These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.
To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.
Prophylactic measures to prevent you getting the error again
The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR
package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.
Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.
Common syntactic mistakes that generate these errors
Mismatched parentheses, braces or brackets
If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.
{}}
## Error: unexpected '}' in "{}}"
{{}} # OK
Missing *
when doing multiplication
This is a common mistake by mathematicians.
5x
Error: unexpected symbol in "5x"
5*x # OK
Not wrapping if, for, or return values in parentheses
This is a common mistake by MATLAB users. In R, if
, for
, return
, etc., are functions, so you need to wrap their contents in parentheses.
if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK
Not using multiple lines for code
Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.
x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK
else
starting on a new line
In an if
-else
statement, the keyword else
must appear on the same line as the end of the if
block.
if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"
if(TRUE) 1 else 2 # OK
if(TRUE)
{
1
} else # also OK
{
2
}
=
instead of ==
=
is used for assignment and giving values to function arguments. ==
tests two values for equality.
if(x = 0) {}
## Error: unexpected '=' in "if(x ="
if(x == 0) {} # OK
Missing commas between arguments
When calling a function, each argument must be separated by a comma.
c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK
Not quoting file paths
File paths are just strings. They need to be wrapped in double or single quotes.
path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK
Quotes inside strings
This is a common problem when trying to pass quoted values to the shell via system
, or creating quoted xPath
or sql
queries.
Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.
"x"y"
## Error: unexpected symbol in ""x"y"
"x\"y" # OK
'x"y' # OK
Using curly quotes
So-called "smart" quotes are not so smart for R programming.
path.expand(“~”)
## Error: unexpected input in "path.expand(“"
path.expand("~") # OK
Using non-standard variable names without backquotes
?make.names
describes what constitutes a valid variable name. If you create a non-valid variable name (using assign
, perhaps), then you need to access it with backquotes,
assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK
This also applies to column names in data frames created with check.names = FALSE
.
dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y` # also OK
It also applies when passing operators and other special values to functions. For example, looking up help on %in%
.
?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK
Sourcing non-R code
The source
function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table
.
source(textConnection("x y"))
## Error in source(textConnection("x y")) :
## textConnection("x y"):1:3: unexpected symbol
## 1: x y
## ^
Corrupted RStudio desktop file
RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop
file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.
Using expression without paste in mathematical plot annotations
When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath
page. Otherwise the contents should be contained inside a call to paste.
plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK
You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources
will throw the exception :
// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");
// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception
Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");
Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.
By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.
Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.
Hope that helps.
Regards
Use RGB values combined with opacity to get the transparency that you wish.
For instance,
<div style=" background: rgb(255, 0, 0) ; opacity: 0.2;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.4;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.6;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.8;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 1;"> </div>
Similarly, with actual values without opacity, will give the below.
<div style=" background: rgb(243, 191, 189) ; "> </div>
<div style=" background: rgb(246, 143, 142) ; "> </div>
<div style=" background: rgb(249, 95 , 94) ; "> </div>
<div style=" background: rgb(252, 47, 47) ; "> </div>
<div style=" background: rgb(255, 0, 0) ; "> </div>
You can have a look at this WORKING EXAMPLE.
Now, if we specifically target your issue, here is the WORKING DEMO SPECIFIC TO YOUR ISSUE.
The HTML
<div class="social">
<img src="http://www.google.co.in/images/srpr/logo4w.png" border="0" />
</div>
The CSS:
social img{
opacity:0.5;
}
.social img:hover {
opacity:1;
background-color:black;
cursor:pointer;
background: rgb(255, 0, 0) ; opacity: 0.5;
}
Hope this helps Now.
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script language='javascript'>
jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
return this.each(function() {
var select = this;`enter code here`
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,'gi');
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
if (selectSingleMatch === true &&
$(select).children().length === 1) {
$(select).children().get(0).selected = true;
}
});
});
};
$(function() {
$('#selectorHtmlElement').filterByText($('#textboxFiltr2'), true);
});
</script>
I will add an option to VitalyB's answer:
Option 3
Via npm. If you run your commands via npm, then you could add this setup to your package.json (check out also the webpack.config.js there too). For developing run npm start
, no need to copy index.html in this case because the web server will be run from the source files directory, and the bundle.js will be available from the same place (the bundle.js will live in memory only but will available as if it was located together with index.html). For production run npm run build
and a dist folder will contain your bundle.js and index.html gets copied with good old cp-command, as you can see below:
"scripts": {
"test": "NODE_ENV=test karma start",
"start": "node node_modules/.bin/webpack-dev-server --content-base app",
"build": "NODE_ENV=production node node_modules/.bin/webpack && cp app/index.html dist/index.html"
}
Update: Option 4
There is a copy-webpack-plugin, as described in this Stackoverflow answer
But generally, except for the very "first" file (like index.html) and larger assets (like large images or video), include the css, html, images and so on directly in your app via require
and webpack will include it for you (well, after you set it up correctly with loaders and possibly plugins).
Could not get this to work until I put Authorization in single quotes:
axios.get(URL, { headers: { 'Authorization': AuthStr } })
WebElement drop_down =driver.findElement(By.id("Category"));
Select se = new Select(drop_down);
for(int i=0 ;i<se.getOptions().size(); i++)
System.out.println(se.getOptions().get(i).getAttribute("value"));
An alternative to jcoby's proposal would be:
class NilClass
def nil_or_empty?
true
end
end
class String
def nil_or_empty?
empty?
end
end
Option 2 is correct: The nested <ul>
is a child of the <li>
it belongs in.
If you validate, option 1 comes up as an error in html 5 -- credit: user3272456
<ul>
as child of <li>
The proper way to make HTML nested list is with the nested <ul>
as a child of the <li>
to which it belongs. The nested list should be inside of the <li>
element of the list in which it is nested.
<ul>
<li>Parent/Item
<ul>
<li>Child/Subitem
</li>
</ul>
</li>
</ul>
A list item can contain another entire list — this is known as "nesting" a list. It is useful for things like tables of contents, such as the one at the start of this article:
- Chapter One
- Section One
- Section Two
- Section Three
- Chapter Two
- Chapter Three
The key to nesting lists is to remember that the nested list should relate to one specific list item. To reflect that in the code, the nested list is contained inside that list item. The code for the list above looks something like this:
<ol>
<li>Chapter One
<ol>
<li>Section One</li>
<li>Section Two </li>
<li>Section Three </li>
</ol>
</li>
<li>Chapter Two</li>
<li>Chapter Three </li>
</ol>
Note how the nested list starts after the <li>
and the text of the containing list item (“Chapter One”); then ends before the </li>
of the containing list item. Nested lists often form the basis for website navigation menus, as they are a good way to define the hierarchical structure of the website.
Theoretically you can nest as many lists as you like, although in practice it can become confusing to nest lists too deeply. For very large lists, you may be better off splitting the content up into several lists with headings instead, or even splitting it up into separate pages.
I stopped using DECODE
several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN
.
However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.
select a, b, decode(a, b, 'true', 'false') as same
from t;
A B SAME
------ ------ -----
1 1 true
1 0 false
1 false
null null true
As of Notepad++ 5.9 they added a feature to 'Remove Unmarked Lines' which can be used to strip away everything that you don't want along with some search and replaces for the other text on each value line.
You can also do a similar thing using Search-->Bookmark-->Copy Bookmarked Lines
So technically you still cannot copy marked text, but you can bookmark lines with marked text and then perform various operations on bookmarked or unmarked lines.
There is no need to use any tool !! We can follow the simple way.
I do not know which tool built your self-extracting Setup program and so, I will have to provide a general response.
Most programs of this nature extract the package file (.msi) into the TEMP directory. This behavior is the default behavior of InstallShield Developer.
Without additional information, I would recommend that you simply launch the setup and once the first MSI dialog is displayed, you can examine your TEMP directory for a newly created sub-directory or MSI file. Before cancelling/stopping an installer just copy that MSI file from TEMP folder. After that you can cancel the installation.
Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException
this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original).
Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.
public static void main(String[] args) throws IOException {
String destFolderPath = "D:/TestFile/abc";
String fileName = "pqr.xlsx";
String sourceFilePath= "D:/TestFile/xyz.xlsx";
File f = new File(destFolderPath);
if(f.mkdir()){
System.out.println("Directory created!!!!");
}
else {
System.out.println("Directory Exists!!!!");
}
f= new File(destFolderPath,fileName);
if(f.createNewFile()) {
System.out.println("File Created!!!!");
} else {
System.out.println("File exists!!!!");
}
Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
System.out.println("Copy done!!!!!!!!!!!!!!");
}
You can always write it like this
String[] errorSoon = {"Hello","World"};
For (int x=0;x<errorSoon.length;x++) // in this way u create a for loop that would like display the elements which are inside the array errorSoon.oh errorSoon.length is the same as errorSoon<2
{
System.out.println(" "+errorSoon[x]); // this will output those two words, at the top hello and world at the bottom of hello.
}
You need to click on the MinGW compiler when running the code. Failure to do this will cause the launch failed binary not found error.
I hope this will help you
$json_ps = '{"courseList":[
{"course":"1", "course_data1":"Computer Systems(Networks)"},
{"course":"2", "course_data2":"Audio and Music Technology"},
{"course":"3", "course_data3":"MBA Digital Marketing"}
]}';
Use Json decode function
$json_pss = json_decode($json_ps, true);
Looping over JSON array in php
foreach($json_pss['courseList'] as $pss_json)
{
echo '<br>' .$course_data1 = $pss_json['course_data1']; exit;
}
Result: Computer Systems(Networks)
Span is an inline element. It has no width or height.
You could turn it into a block-level element, then it will accept your dimension directives.
span.product__specfield_8_arrow
{
display: inline-block; /* or block */
}
For Android .so
files, the NDK toolchain comes with the required tools mentioned in the other answers: readelf
, objdump
and nm
.
First List the Variable that you want to use them in Script task at ReadOnlyVariables in the Script task editor and Edit the Script
To use your ReadOnlyVariables in script code
String codeVariable = Dts.Variables["User::VariableNameinSSIS"].Value.ToString();
this line of code will treat the ssis package variable as a string.
I had this issue ..
A working solution is to change ownership of /usr/local
to current user instead of root
by:
sudo chown -R $(whoami):admin /usr/local
But really this is not a proper way. Mainly if your machine is a server or multiple-user.
My suggestion is to change the ownership as above and do whatever you want to implement with Brew .. ( update, install ... etc ) then reset ownership back to root as:
sudo chown -R root:admin /usr/local
Thats would solve the issue and keep ownership set in proper set.
declare @lastweek datetime
declare @now datetime
set @now = getdate()
set @lastweek = dateadd(day,-7,@now)
SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN @lastweek AND @now
GROUP BY URLx
ORDER BY Count DESC;
The following should do the trick for both single character and multiple character searches:
CREATE FUNCTION dbo.CountOccurrences
(
@SearchString VARCHAR(1000),
@SearchFor VARCHAR(1000)
)
RETURNS TABLE
AS
RETURN (
SELECT COUNT(*) AS Occurrences
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY O.object_id) AS n
FROM sys.objects AS O
) AS N
JOIN (
VALUES (@SearchString)
) AS S (SearchString)
ON
SUBSTRING(S.SearchString, N.n, LEN(@SearchFor)) = @SearchFor
);
GO
---------------------------------------------------------------------------------------
-- Test the function for single and multiple character searches
---------------------------------------------------------------------------------------
DECLARE @SearchForComma VARCHAR(10) = ',',
@SearchForCharacters VARCHAR(10) = 'de';
DECLARE @TestTable TABLE
(
TestData VARCHAR(30) NOT NULL
);
INSERT INTO @TestTable
(
TestData
)
VALUES
('a,b,c,de,de ,d e'),
('abc,de,hijk,,'),
(',,a,b,cde,,');
SELECT TT.TestData,
CO.Occurrences AS CommaOccurrences,
CO2.Occurrences AS CharacterOccurrences
FROM @TestTable AS TT
OUTER APPLY dbo.CountOccurrences(TT.TestData, @SearchForComma) AS CO
OUTER APPLY dbo.CountOccurrences(TT.TestData, @SearchForCharacters) AS CO2;
The function can be simplified a bit using a table of numbers (dbo.Nums):
RETURN (
SELECT COUNT(*) AS Occurrences
FROM dbo.Nums AS N
JOIN (
VALUES (@SearchString)
) AS S (SearchString)
ON
SUBSTRING(S.SearchString, N.n, LEN(@SearchFor)) = @SearchFor
);
I'll answer my own question for the first time. I found an example straight from the source. Please forgive the poor indentation. I wasn't sure how to indent properly when copying and pasting. The code comes straight from Express multipart/form-data
example on GitHub.
// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');
/**
* Module dependencies.
*/
var express = require('../../lib/express')
, form = require('connect-form');
var app = express.createServer(
// connect-form (http://github.com/visionmedia/connect-form)
// middleware uses the formidable middleware to parse urlencoded
// and multipart form data
form({ keepExtensions: true })
);
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
// connect-form adds the req.form object
// we can (optionally) define onComplete, passing
// the exception (if any) fields parsed, and files parsed
req.form.complete(function(err, fields, files){
if (err) {
next(err);
} else {
console.log('\nuploaded %s to %s'
, files.image.filename
, files.image.path);
res.redirect('back');
}
});
// We can add listeners for several form
// events such as "progress"
req.form.on('progress', function(bytesReceived, bytesExpected){
var percent = (bytesReceived / bytesExpected * 100) | 0;
process.stdout.write('Uploading: %' + percent + '\r');
});
});
app.listen(3000);
console.log('Express app started on port 3000');
As well as the solution from marc_s, you can also use osql or sqlcmd
This includes headers and it can act like bcp using -Q and -o. However, they don't support format files like bcp.
This makes a list of all the occurrences (also overlapping) in the string and counts them
def num_occ(str1, str2):
l1, l2 = len(str1), len(str2)
return len([str1[i:i + l2] for i in range(l1 - l2 + 1) if str1[i:i + l2] == str2])
Example:
str1 ='abcabcd'
str2 = 'bc'
will create this list but save only the BOLD values:
[ab, bc, ca, ab, bc, cd]
that will return:
len([bc, bc])
The package can be uninstalled using the same uninstall or rm command that can be used for removing installed packages. The only thing to keep in mind is that the link needs to be uninstalled globally - the --global
flag needs to be provided.
In order to uninstall the globally linked foo
package, the following command can be used (using sudo
if necessary, depending on your setup and permissions)
sudo npm rm --global foo
This will uninstall the package.
To check whether a package is installed, the npm ls
command can be used:
npm ls --global foo
Make use of *(B)
instead of *B[0]
.
Here, *(B+i)
implies B[i]
and *(B)
implies B[0
], that is *(B+0)=*(B)=B[0]
.
#include <stdio.h>
int func(int *B){
*B = 5;
// if you want to modify ith index element in the array just do *(B+i)=<value>
}
int main(void){
int B[10] = {};
printf("b[0] = %d\n\n", B[0]);
func(B);
printf("b[0] = %d\n\n", B[0]);
return 0;
}
Variable declaration. Initially, it was short for "dimension", which is not a term that is used in programming (outside of this specific keyword) to any significant degree.
http://in.answers.yahoo.com/question/index?qid=20090310095555AANmiAZ
For anything with requests to URLs you might want to check out requests. For JSON in particular:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
Pure CSS:
.app-tooltip {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.app-tooltip:before {_x000D_
content: attr(data-title);_x000D_
background-color: rgba(97, 97, 97, 0.9);_x000D_
color: #fff;_x000D_
font-size: 12px;_x000D_
padding: 10px;_x000D_
position: absolute;_x000D_
bottom: -50px;_x000D_
opacity: 0;_x000D_
transition: all 0.4s ease;_x000D_
font-weight: 500;_x000D_
z-index: 2;_x000D_
}_x000D_
_x000D_
.app-tooltip:after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
left: 5px;_x000D_
bottom: -16px;_x000D_
border-style: solid;_x000D_
border-width: 0 10px 10px 10px;_x000D_
border-color: transparent transparent rgba(97, 97, 97, 0.9) transparent;_x000D_
transition: all 0.4s ease;_x000D_
}_x000D_
_x000D_
.app-tooltip:hover:after,_x000D_
.app-tooltip:hover:before {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div href="#" class="app-tooltip" data-title="Your message here"> Test here</div>
_x000D_
I agree with @adietisheim and the rest of people that suggest HttpClient.
I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.
An example of code to make a put http call is as follows:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(URI);
StringEntity input = new StringEntity(XML);
input.setContentType(CONTENT_TYPE);
putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);
In python, bool(sequence)
is False
if the sequence is empty. Since strings are sequences, this will work:
cookie = ''
if cookie:
print "Don't see this"
else:
print "You'll see this"
One way to do this without using VUE-CLI is to bundle the all script files into one fat js file and then reference that big fat javascript file into main template file.
I prefer to use webpack as a bundler and create a webpack.conig.js in the root directory of project. All the configs such as entry point, output file, loaders, etc.. are all stored in that config file. After that, I add a script in package.json file that uses webpack.config.js file for webpack configs and start watching files and create a Js bundled file into mentioned location in webpack.config.js file.
try getHibernateTemplate().saveOrUpdate()
I would suggest you to have a look at RSHD
You do not need to bother for a client, Windows has it by default.
Use this Format as per your requirements:
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay"
"arrayOneName" : [
{
"Id" : 1,
"Employee" : "EmpOne",
"Deptartment" : "HR"
},
{
"Id" : 2,
"Employee" : "EmpTwo",
"Deptartment" : "IT"
},
{
"Id" : 3,
"Employee" : "EmpThree",
"Deptartment" : "Sales"
}
],
"arrayTwoName": [
{
"Product": "3",
"Price": "6790"
}
],
"arrayThreeName" : [
"name1", "name2", "name3", "name4" // For Strings
],
"arrayFourName" : [
1, 2, 3, 4 // For Numbers
]
}
Remember to use this in POST with proper endpoint. Also, RAW selected and JSON(application/json) in Body Tab.
Like THIS:
Update 1:
I don't think multiple @RequestBody is allowed or possible.
@RequestBody parameter must have the entire body of the request and bind that to only one object.
You have to use something like Wrapper Object for this to work.
This is something you solve in the "controller", which is the point of logicless templating.
// some function that retreived data through ajax
function( view ){
if ( !view.avatar ) {
// DEFAULTS can be a global settings object you define elsewhere
// so that you don't have to maintain these values all over the place
// in your code.
view.avatar = DEFAULTS.AVATAR;
}
// do template stuff here
}
This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)
Another option is to do the following:
// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;
And in the template:
{{#hasAvatar}}
SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
SHOW DEFAULT
{{/noAvatar}}
But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)
It seems that bames53's answer can be extended to defining integer and non-integer constant values in namespace and class declarations even if they get included in multiple source files. It is not necessary to put the declarations in a header file but the definitions in a source file. The following example works for Microsoft Visual Studio 2015, for z/OS V2.2 XL C/C++ on OS/390, and for g++ (GCC) 8.1.1 20180502 on GNU/Linux 4.16.14 (Fedora 28). Note that the constants are declared/defined in only a single header file that gets included in multiple source files.
In foo.cc:
#include <cstdio> // for puts
#include "messages.hh"
#include "bar.hh"
#include "zoo.hh"
int main(int argc, const char* argv[])
{
puts("Hello!");
bar();
zoo();
puts(Message::third);
return 0;
}
In messages.hh:
#ifndef MESSAGES_HH
#define MESSAGES_HH
namespace Message {
char const * const first = "Yes, this is the first message!";
char const * const second = "This is the second message.";
char const * const third = "Message #3.";
};
#endif
In bar.cc:
#include "messages.hh"
#include <cstdio>
void bar(void)
{
puts("Wow!");
printf("bar: %s\n", Message::first);
}
In zoo.cc:
#include <cstdio>
#include "messages.hh"
void zoo(void)
{
printf("zoo: %s\n", Message::second);
}
In bar.hh:
#ifndef BAR_HH
#define BAR_HH
#include "messages.hh"
void bar(void);
#endif
In zoo.hh:
#ifndef ZOO_HH
#define ZOO_HH
#include "messages.hh"
void zoo(void);
#endif
This yields the following output:
Hello!
Wow!
bar: Yes, this is the first message!
zoo: This is the second message.
Message #3.
The data type char const * const
means a constant pointer to an array of constant characters. The first const
is needed because (according to g++) "ISO C++ forbids converting a string constant to 'char*'". The second const
is needed to avoid link errors due to multiple definitions of the (then insufficiently constant) constants. Your compiler might not complain if you omit one or both of the const
s, but then the source code is less portable.
"java.lang.SecurityException: class" org.hamcrest.Matchers "'s signer information does not match signer information of other classes in the same package"
Do it: Right-click on your package click on Build Path -> Configure Build Path Click on the Libraries tab Remove JUnit Apply and close Ready.
function updateTextArea() {
var allVals = $('#c_b :checked').map(function() {
return $(this).val();
}).get();
$('#t').val(allVals)
}
$(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
Another advantage of CXF: it connects to web servers using NTLMV2 authentication out of the box. (used by Windows 2008 & up) Before using CXF, I hacked Axis2 to use HTTPClient V4 + JCIFS to make this possible.
Not Knowing all of your requirements. For example, are you trying to uniquely identify a computer from all of the computers in the world, or are you just trying to uniquely identify a computer from a set of users of your application. Also, can you create files on the system?
If you are able to create a file. You could create a file and use the creation time of the file as your unique id. If you create it in user space then it would uniquely identify a user of your application on a particular machine. If you created it somewhere global then it could uniquely identify the machine.
Again, as most things, How fast is fast enough.. or in this case, how unique is unique enough.
This error can be because of contract mismatch. Consider the three layered application below...
UI Layer
|
Process Layer
|
Data Access Layer
-> Contract Between Process and UI layer has the same enum with missing (Onhold = 3). Enum: Start = 1, Stop = 2.
-> Contract Between Data Access And Process layer has enum Enum: Start = 1,Stop = 2,Onhold = 3.
In this case we will get the same error in process layer response.
The same error comes in other contract mismatch in multilayered application.
CommonsWare is right, but in my opinion this is a (bug)poor way to say: "The apk installed on the device is signed with a different certificate then the new one you are trying to install".
This is probably a new bug since in the past it used to ask whether or not to uninstall the app from the device due to wrong certificate.
The solution as painful as it may be would be to uninstall the app it manually.
Also what we've done for the sake of team development, we added the debug keystore to our repository, and point gradle to use it like so:
android {
...
signingConfigs {
debug {
storeFile file("../certificates/debug.keystore")
}
}
...
buildTypes {
debug {
signingConfig signingConfigs.debug
}
}
...
}
And now when passing devices between team members, we all use the same debug certificate, so there is no issue. :)
I use a dot(.) to concate string and variable. like this-
echo "Hello ".$var;
Sometimes, I use curly braces to concate string and variable that looks like this-
echo "Hello {$var}";
In Javascript you can do like this
function submitRequest(buttonId) {
if (document.getElementById(buttonId) == null
|| document.getElementById(buttonId) == undefined) {
return;
}
if (document.getElementById(buttonId).dispatchEvent) {
var e = document.createEvent("MouseEvents");
e.initEvent("click", true, true);
document.getElementById(buttonId).dispatchEvent(e);
} else {
document.getElementById(buttonId).click();
}
}
and you can use it like
submitRequest("target-element-id");
i solved with a max-width
in my main css-file.
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
max-width: 280px;
}
It's a simple solution with little "code"
Simple Answer: NO. You cannot help ad hoc queries on a 238 column table with a 50% Fill Factor on the Clustered Index.
Detailed Answer:
As I have stated in other answers on this topic, Index design is both Art and Science and there are so many factors to consider that there are few, if any, hard and fast rules. You need to consider: the volume of DML operations vs SELECTs, disk subsystem, other indexes / triggers on the table, distribution of data within the table, are queries using SARGable WHERE conditions, and several other things that I can't even remember right now.
I can say that no help can be given for questions on this topic without an understanding of the Table itself, its indexes, triggers, etc. Now that you have posted the table definition (still waiting on the Indexes but the Table definition alone points to 99% of the issue) I can offer some suggestions.
First, if the table definition is accurate (238 columns, 50% Fill Factor) then you can pretty much ignore the rest of the answers / advice here ;-). Sorry to be less-than-political here, but seriously, it's a wild goose chase without knowing the specifics. And now that we see the table definition it becomes quite a bit clearer as to why a simple query would take so long, even when the test queries (Update #1) ran so quickly.
The main problem here (and in many poor-performance situations) is bad data modeling. 238 columns is not prohibited just like having 999 indexes is not prohibited, but it is also generally not very wise.
Recommendations:
ANSI_PADDING OFF
is disturbing, not to mention inconsistent within the table due to the various column additions over time. Not sure if you can fix that now, but ideally you would always have ANSI_PADDING ON
, or at the very least have the same setting across all ALTER TABLE
statements.PRIMARY
as that is where SQL SERVER stores all of its data and meta-data about your objects. You create your Table and Clustered Index (as that is the data for the table) on [Tables]
and all Non-Clustered indexes on [Indexes]
WHERE
condition, then consider moving that to the leading column of the clustered index. Assuming that it is used more often than "ER101_ORD_NBR". If "ER101_ORD_NBR" is used more often then keep it. It just seems, assuming that the field names mean "OrganizationCode" and "OrderNumber", that "OrgCode" is a better grouping that might have multiple "OrderNumbers" within it.CHAR(2)
instead of VARCHAR(2)
as it will save a byte in the row header which tracks variable width sizes and adds up over millions of rows.SELECT *
will hurt performance. Not only due to it requiring SQL Server to return all columns and hence be more likely to do a Clustered Index Scan regardless of your other indexes, but it also takes SQL Server time to go to the table definition and translate *
into all of the column names. It should be slightly faster to specify all 238 column names in the SELECT
list though that won't help the Scan issue. But do you ever really need all 238 columns at the same time anyway?Good luck!
UPDATE
For the sake of completeness to the question "how to improve performance on a large table for ad-hoc queries", it should be noted that while it will not help for this specific case, IF someone is using SQL Server 2012 (or newer when that time comes) and IF the table is not being updated, then using Columnstore Indexes is an option. For more details on that new feature, look here:
http://msdn.microsoft.com/en-us/library/gg492088.aspx (I believe these were made to be updateable starting in SQL Server 2014).
UPDATE 2
Additional considerations are:
INT
, BIGINT
, TINYINT
, SMALLINT
, CHAR
, NCHAR
, BINARY
, DATETIME
, SMALLDATETIME
, MONEY
, etc) and well over 50% of the rows are NULL
, then consider enabling the SPARSE
option which became available in SQL Server 2008. Please see the MSDN page for Use Sparse Columns for details.JSONP allows you to specify a callback function that is passed your JSON object. This allows you to bypass the same origin policy and load JSON from an external server into the JavaScript on your webpage.
Nowadays, people use DESC
instead of DESCRIPTION
. For example:-
DESC users;
JSON.stringify
takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>
tag to get newlines to show.
For window user, Please run complete command to convert *.dot file to png:
C:\Program Files (x86)\Graphviz2.38\bin\dot.exe" -Tpng sampleTest.dot > sampletest.png.....
I have found a bug in solgraph that it is utilizing older version of solidity-parser that does not seem to be intelligent enough to capture new enhancement done for solidity programming language itself e.g. emit keyword for Event
I think you need to set symbreaks = FALSE
That should allow for asymmetrical color scales.
self
is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main()
, you first have to instantiate an object of your class and call the function on the object.
Further, your function setavalue
should be in __init___
, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name
class ;)
class Name:
def __init__(self):
self.myname = "harry"
def printaname(self):
print "Name", self.myname
def main(self):
self.printaname()
if __name__ == "__main__":
objName = Name()
objName.main()
Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.
If your destination element is empty and will only contain the <svg>
tag you could consider using ng-bind-html
as follow :
Declare your HTML tag in the directive scope variable
link: function (scope, iElement, iAttrs) {
scope.svgTag = '<svg width="600" height="100" class="svg"></svg>';
...
}
Then, in your directive template, just add the proper attribute at the exact place you want to append the svg tag :
<!-- start of directive template code -->
...
<!-- end of directive template code -->
<div ng-bind-html="svgTag"></div>
Don't forget to include ngSanitize
to allow ng-bind-html
to automatically parse the HTML string to trusted HTML and avoid insecure code injection warnings.
See official documentation for more details.
You can use Process.GetProcesses()
to get the currently running processes, then Process.Kill()
to kill a process.
link.onclick = function() { onClickLink(i+''); };
Is a closure and stores a reference to the variable i
, not the value that i
holds when the function is created. One solution would be to wrap the contents of the for
loop in a function do this:
for (var i = 0; i < 10; i++) (function(i) {
var link = document.createElement('a');
link.setAttribute('href', '#');
link.innerHTML = i + '';
link.onclick= function() { onClickLink(i+'');};
div.appendChild(link);
div.appendChild(document.createElement('BR'));
}(i));
show all branches and commit
git log --branches --oneline
show last commit
git log --branches -1 --oneline
show before last commit
git log --branches -2 --oneline
There is another solution from the pandas documentation (that I don't see here),
using the .append
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
A B
0 1 2
1 3 4
>>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
A B
0 5 6
1 7 8
>>> df.append(df2, ignore_index=True)
A B
0 1 2
1 3 4
2 5 6
3 7 8
The ignore_index=True
is used to ignore the index of the appended dataframe, replacing it with the next index available in the source one.
If there are different column names, Nan
will be introduced.
Following Python code worked for me. To check the ODBC connection, I first created a 4 line C# console application as listed below.
Python Code
import pandas as pd
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;")
df = pd.read_sql_query('select TOP 10 * from dbo.Table WHERE Patient_Key > 1000', cnxn)
df.head()
Calling a Stored Procedure
dfProcResult = pd.read_sql_query('exec dbo.usp_GetPatientProfile ?', cnxn, params=['MyParam'] )
C# Program to Check ODBC Connection
static void Main(string[] args)
{
string connectionString = "Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;";
OdbcConnection cn = new OdbcConnection(connectionString);
cn.Open();
cn.Close();
}
I realize this is very old, but here is my solution which is based on the expressions/microsoft interactivity and interactions name spaces.
First, I followed the instructions at this link to place interactivity triggers into a style.
Then it comes down to this
<Style x:Key="baseTextBox" TargetType="TextBox">
<Setter Property="gint:InteractivityItems.Template">
<Setter.Value>
<gint:InteractivityTemplate>
<gint:InteractivityItems>
<gint:InteractivityItems.Triggers>
<i:EventTrigger EventName="GotKeyboardFocus">
<ei:CallMethodAction MethodName="SelectAll"/>
</i:EventTrigger>
<i:EventTrigger EventName="PreviewMouseLeftButtonDown">
<ei:CallMethodAction MethodName="TextBox_PreviewMouseLeftButtonDown"
TargetObject="{Binding ElementName=HostElementName}"/>
</i:EventTrigger>
</gint:InteractivityItems.Triggers>
</gint:InteractivityItems>
</gint:InteractivityTemplate>
</Setter.Value>
</Setter>
</Style>
and this
public void TextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
TextBox tb = e.Source as TextBox;
if((tb != null) && (tb.IsKeyboardFocusWithin == false))
{
tb.Focus();
e.Handled = true;
}
}
In my case, I have a user control where the text boxes are that has a code-behind. The code-behind has the handler function. I gave my user control a name in XAML, and I am using that name for the element. This is working perfectly for me. Simply apply the style to any TextBox
where you would like to have all the text selected when you click in the TextBox
.
The first CallMethodAction
calls the text box's SelectAll
method when the GotKeyboardFocus
event on the TextBox
fires.
I hope this helps.
In the latest version of JAVA this is how you do it:
nir.length //is the first dimension
nir[0].length //is the second dimension
a=[]
b=int(input())
for i in range(b):
c=int(input())
a.append(c)
The above code snippets is easy method to get values from the user.
External return type declaration to use with multiple functions:
type ValidationReturnType = string | boolean;
function isEqual(number1: number, number2: number): ValidationReturnType {
return number1 == number2 ? true : 'Numbers are not equal.';
}
I made a little test (Perl v5.20.1 under FreeBSD in VM) calling the following blocks 1.000.000 times each:
A
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
my $now = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year+1900, $mon+1, $mday, $hour, $min, $sec);
B
my $now = strftime('%Y%m%d%H%M%S',localtime);
C
my $now = Time::Piece::localtime->strftime('%Y%m%d%H%M%S');
with the following results:
A: 2 seconds
B: 11 seconds
C: 19 seconds
This is of course not a thorough test or benchmark, but at least it is reproducable for me, so even though it is more complicated, I'd prefer the first method if generating a datetimestamp is required very often.
Calling (eg. under FreeBSD 10.1)
my $now = `date "+%Y%m%d%H%M%S" | tr -d "\n"`;
might not be such a good idea because it is not OS-independent and takes quite some time.
Best regards, Holger
No there's not and developers still don't know why google doesn't pay attention to this request!
As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!
After reading the answers above I wrote a Q&D shell script (should work on sh and bash) to run g++ on PGM.cpp to produce executable image PGM. It assumes that the last argument on the command line is the file name (.cpp is optional) and all other arguments are options.
#!/bin/sh
if [ $# -lt 1 ]
then
echo "Usage: `basename $0` [opt] pgm runs g++ to compile pgm[.cpp] into pgm"
exit 2
fi
OPT=
PGM=
# PGM is the last argument, all others are considered options
for F; do OPT="$OPT $PGM"; PGM=$F; done
DIR=`dirname $PGM`
PGM=`basename $PGM .cpp`
# put -o first so it can be overridden by -o specified in OPT
set -x
g++ -o $DIR/$PGM $OPT $DIR/$PGM.cpp
The following is a very simple C++ example that shows that if you want to use a function to set a pointer to point to an object, you need a pointer to a pointer. Otherwise, the pointer will keep reverting to null.
(A C++ answer, but I believe it's the same in C.)
(Also, for reference: Google("pass by value c++") = "By default, arguments in C++ are passed by value. When an argument is passed by value, the argument's value is copied into the function's parameter.")
So we want to set the pointer b
equal to the string a
.
#include <iostream>
#include <string>
void Function_1(std::string* a, std::string* b) {
b = a;
std::cout << (b == nullptr); // False
}
void Function_2(std::string* a, std::string** b) {
*b = a;
std::cout << (b == nullptr); // False
}
int main() {
std::string a("Hello!");
std::string* b(nullptr);
std::cout << (b == nullptr); // True
Function_1(&a, b);
std::cout << (b == nullptr); // True
Function_2(&a, &b);
std::cout << (b == nullptr); // False
}
// Output: 10100
What happens at the line Function_1(&a, b);
?
The "value" of &main::a
(an address) is copied into the parameter std::string* Function_1::a
. Therefore Function_1::a
is a pointer to (i.e. the memory address of) the string main::a
.
The "value" of main::b
(an address in memory) is copied into the parameter std::string* Function_1::b
. Therefore there are now 2 of these addresses in memory, both null pointers. At the line b = a;
, the local variable Function_1::b
is then changed to equal Function_1::a
(= &main::a
), but the variable main::b
is unchanged. After the call to Function_1
, main::b
is still a null pointer.
What happens at the line Function_2(&a, &b);
?
The treatment of the a
variable is the same: within the function, Function_2::a
is the address of the string main::a
.
But the variable b
is now being passed as a pointer to a pointer. The "value" of &main::b
(the address of the pointer main::b
) is copied into std::string** Function_2::b
. Therefore within Function_2, dereferencing this as *Function_2::b
will access and modify main::b
. So the line *b = a;
is actually setting main::b
(an address) equal to Function_2::a
(= address of main::a
) which is what we want.
If you want to use a function to modify a thing, be it an object or an address (pointer), you have to pass in a pointer to that thing. The thing that you actually pass in cannot be modified (in the calling scope) because a local copy is made.
(An exception is if the parameter is a reference, such as std::string& a
. But usually these are const
. Generally, if you call f(x)
, if x
is an object you should be able to assume that f
won't modify x
. But if x
is a pointer, then you should assume that f
might modify the object pointed to by x
.)
There's a python module especially made for reading and writing to and from binary encoded data called 'struct'. Since versions of Python under 2.6 doesn't support str.format, a custom method needs to be used to create binary formatted strings.
import struct
# binary string
def bstr(n): # n in range 0-255
return ''.join([str(n >> x & 1) for x in (7,6,5,4,3,2,1,0)])
# read file into an array of binary formatted strings.
def read_binary(path):
f = open(path,'rb')
binlist = []
while True:
bin = struct.unpack('B',f.read(1))[0] # B stands for unsigned char (8 bits)
if not bin:
break
strBin = bstr(bin)
binlist.append(strBin)
return binlist
As far as I can see, this would be possible only using height: (some em value); overflow: hidden
and even then it wouldn't have the fancy ...
at the end.
If that is not an option, I think it's impossible without some server side pre-processing (difficult because text flow is impossible to predict reliably) or jQuery (possible but probably complicated).
First you will need to install node definitions for Typescript. You can find the definitions file here:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts
Once you've got file, just add the reference to your .ts
file like this:
/// <reference path="path/to/node.d.ts" />
Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts
can look like this:
/// <reference path="path/to/node.d.ts" />
class MyClass {
// Here we import the File System module of node
private fs = require('fs');
constructor() { }
createFile() {
this.fs.writeFile('file.txt', 'I am cool!', function(err) {
if (err) {
return console.error(err);
}
console.log("File created!");
});
}
showFile() {
this.fs.readFile('file.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
}
}
// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();
Once you transpile your .ts
file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:
> node myClass.js
I couldn't leave this question here with out a single statement using the modulo operator.
def rot13(s):
return ''.join([chr(x.islower() and ((ord(x) - 84) % 26) + 97
or x.isupper() and ((ord(x) - 52) % 26) + 65
or ord(x))
for x in s])
This is not pythonic nor good practice, but it works!
>> rot13("Hello World!")
Uryyb Jbeyq!
I had a very similar problem, I had an array ready to be posted. in my post function I had this:
json = JSON.stringfy(json);
the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json)
in every validation and realized that the json was treated as a string instead of an object.
In conclution i shouldn't have assinged json = JSON.stringfy(json)
instead i assigned it to another variable.
var aux = JSON.stringfy(json);
This way i keep json as an object, and not a string.
A 'docker way' would be to use docker hub automated builds. The Repository Links feature will rebuild your container when an upstream container is rebuilt, and the Webhooks feature will send you a notification.
It looks like the webhooks are limited to HTTP POST calls. You'd need to set up a service to catch them, or maybe use one of the POST to email services out there.
I haven't looked into it, but the new Docker Universal Control Plane might have a feature for detecting updated containers and re-deploying.
WPF only
don't have the exact code to hand, but in a recent project I think I used MouseDown event and simply put this:
frmBorderless.DragMove();
When entering the script's full file spec or its filename on the command line, the shell will use information accessibly by
assoc | grep -i vbs
.vbs=VBSFile
ftype | grep -i vbs
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*
to decide which program to run for the script. In my case it's cscript.exe, in yours it will be wscript.exe - that explains why your WScript.Echos result in MsgBoxes.
As
cscript /?
Usage: CScript scriptname.extension [option...] [arguments...]
Options:
//B Batch mode: Suppresses script errors and prompts from displaying
//D Enable Active Debugging
//E:engine Use engine for executing script
//H:CScript Changes the default script host to CScript.exe
//H:WScript Changes the default script host to WScript.exe (default)
//I Interactive mode (default, opposite of //B)
//Job:xxxx Execute a WSF job
//Logo Display logo (default)
//Nologo Prevent logo display: No banner will be shown at execution time
//S Save current command line options for this user
//T:nn Time out in seconds: Maximum time a script is permitted to run
//X Execute script in debugger
//U Use Unicode for redirected I/O from the console
shows, you can use //E and //S to permanently switch your default host to cscript.exe.
If you are so lazy that you don't even want to type the extension, make sure that the PATHEXT environment variable
set | grep -i vbs
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.tcl;.PSC1
contains .VBS and there is no Converter.cmd (that converts your harddisk into a washing machine) in your path.
Update wrt comment:
If you 'don't want to specify the full path of my vbscript everytime' you may:
cscript p:\ath\to\CONVERTER.VBS
In both cases I would type out the extension to avoid (nasty) surprises.
You can disable the copy paste option with jQuery by the below script:
jQuery("input").attr("onpaste","return false;");
of by using the bellow oppaste attribute into the input fields.
onpaste="return false;"
Addressing Steven's comment to Sam Dufel's answer
Thanks, sounds like that's the way to go. But I just realized that I only want the optional whitespace characters if they follow a newline. So for example, "c\n ats" or "ca\n ts" should match. But wouldn't want "c ats" to match if there is no newline. Any ideas on how that might be done?
This should do the trick:
/c(?:\n\s*)?a(?:\n\s*)?t(?:\n\s*)?s/
See this page for all the different variations of 'cats' that this matches.
You can also solve this using conditionals, but they are not supported in the javascript flavor of regex.
I wanted to show how powerful it can be aside from just checking "-lt".
Example: I used it to calculate time differences take from Windows event view Application log:
Get the difference between the two date times:
PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))
Object created:
PS> $Obj
Days : 0
Hours : 0
Minutes : 31
Seconds : 0
Milliseconds : 0
Ticks : 18600000000
TotalDays : 0.0215277777777778
TotalHours : 0.516666666666667
TotalMinutes : 31
TotalSeconds : 1860
TotalMilliseconds : 1860000
Access an item directly:
PS> $Obj.Minutes
31
This is an old post but I have issues with coming across posts that have some incorrect information/syntax...
If you wanted to do this with a shorcut icon you could just create a shortcut on your desktop for the cmd.exe application. Then append a /K {your command} to the shorcut path.
So a default shorcut target path may look like "%windir%\system32\cmd.exe", just change it to %windir%\system32\cmd.exe /k {commands}
example: %windir%\system32\cmd.exe /k powercfg -lastwake
In this case i would use /k (keep open) to display results.
Arlen was right about the /k (keep open) and /c (close)
You can open a command prompt and type "cmd /?" to see your options.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true
A batch file is kind of overkill for a single command prompt command...
Hope this helps someone else
First, emulate the print stylesheet via your browser's devtools. Instructions can be found here.
Then you'll want to look for extra padding, margin, borders, etc that could be extending the dimensions of your pages beyond the 8.5in x 11in. Pay special attention to whitespace as this will be impossible to detect via the print preview dialog. If there is whitespace that shouldn't be there, right-clicking and inspecting the element under the cursor should highlight the issue (unless it's a margin causing it).
a = '123' if b else '456'
This is what I finally could do for installing psych package in R-3.4.1 when I got the same warning
1:Googled for that package.
2:downloaded it manually having tar.gz extension
3:Chose the option "Package Archive File (.zip;.tar.gz)" for install packages in R
4:browsed locally to the place where it was downloaded and clicked install
You may get a warning: dependencies 'xyz' not available for the package ,then first install those from the repository and then do steps 3-4 .
I did the below changes and works fine for me.
Just add the attribute <iframe src="URL" target="_parent" />
_parent
: this would open embedded page in same window.
_blank
: In different tab
SELECT TOP (@count) * FROM SomeTable
This will only work with SQL 2005+
Simple and Easy. Remove all columns after the 22th.
df.drop(columns=df.columns[22:]) # love it
Ensure you android device has enough memory to install the app. Sometimes it so happens working with multimedia app where the device storage keeps on increasing and you keep wondering about the error.
Therefore, free up some memory and try installing again!
pd.to_numeric
with errors='coerce'
# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s
0 1
1 2
2 3
3 4
4 .
dtype: object
pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 3.0
3 4.0
4 NaN
dtype: float64
If you need the NaN
s filled in, use Series.fillna
.
pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')
0 1
1 2
2 3
3 4
4 0
dtype: float64
Note, downcast='infer'
will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.
From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use
pd.__version__ # '0.24.1' pd.to_numeric(s, errors='coerce').astype('Int32') 0 1 1 2 2 3 3 4 4 NaN dtype: Int32
There are other options to choose from as well, read the docs for more.
DataFrames
If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply
.
# Setup.
np.random.seed(0)
df = pd.DataFrame({
'A' : np.random.choice(10, 5),
'C' : np.random.choice(10, 5),
'B' : ['1', '###', '...', 50, '234'],
'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df
A B C D
0 5 1 9 23
1 0 ### 3 1
2 3 ... 5 ...
3 3 50 2 268
4 7 234 4 $$
df.dtypes
A int64
B object
C int64
D object
dtype: object
df2 = df.apply(pd.to_numeric, errors='coerce')
df2
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
df2.dtypes
A int64
B float64
C int64
D float64
dtype: object
You can also do this with DataFrame.transform
; although my tests indicate this is marginally slower:
df.transform(pd.to_numeric, errors='coerce')
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric
on the non-numeric columns only.
df.dtypes.eq(object)
A False
B True
C False
D True
dtype: bool
cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
# df[c] = pd.to_numeric(df[c], errors='coerce')
df
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
Applying pd.to_numeric
along the columns (i.e., axis=0
, the default) should be slightly faster for long DataFrames.
I just figured out interesting solution:
public class DepthAware<T> : IEnumerable<T>
{
private readonly IEnumerable<T> source;
public DepthAware(IEnumerable<T> source)
{
this.source = source;
this.Depth = 0;
}
public int Depth { get; private set; }
private IEnumerable<T> GetItems()
{
foreach (var item in source)
{
yield return item;
++this.Depth;
}
}
public IEnumerator<T> GetEnumerator()
{
return GetItems().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
// Generic type leverage and extension invoking
public static class DepthAware
{
public static DepthAware<T> AsDepthAware<T>(this IEnumerable<T> source)
{
return new DepthAware<T>(source);
}
public static DepthAware<T> New<T>(IEnumerable<T> source)
{
return new DepthAware<T>(source);
}
}
Usage:
var chars = new[] {'a', 'b', 'c', 'd', 'e', 'f', 'g'}.AsDepthAware();
foreach (var item in chars)
{
Console.WriteLine("Char: {0}, depth: {1}", item, chars.Depth);
}
ng-click "$watch(edit($index), open())"
On Fedora 22, you need to do this instead:
sudo dnf install python-devel
sudo dnf install openldap-devel
NOTE: Using set_fact
as described below sets a fact/variable onto the remote servers that the task is running against. This fact/variable will then persist across subsequent tasks for the entire duration of your playbook.
Also, these facts are immutable (for the duration of the playbook), and cannot be changed once set.
Use set_fact
before your task to set facts which seem interchangeable with variables:
- name: Set Apache URL
set_fact:
apache_url: 'http://example.com/apache'
- name: Download Apache
shell: wget {{ apache_url }}
See http://docs.ansible.com/set_fact_module.html for the official word.
Some Linux distributions don't use the gdb
style debugging symbols. (IIRC they prefer dwarf2
.)
In general, gcc
and gdb
will be in sync as to what kind of debugging symbols they use, and forcing a particular style will just cause problems; unless you know that you need something else, use just -g
.
It's possible to scale NodeJS out to multiple boxes using a pure TCP load balancer (HAProxy) in front of multiple boxes running one NodeJS process each.
If you then have some common knowledge to share between all instances you could use a central Redis store or similar which can then be accessed from all process instances (e.g. from all boxes)
If you want to check if a property exists: hasOwnProperty is the way to go
And since most objects are properties of some other object (eventually leading to the window
object) this can work well for checking if values have been declared.
For example, you can invoke a private constructor inside a friend class or a friend function.
Singleton pattern usually uses it to make sure that nobody creates more instances of the intended type.
Need to add to chosen answer: As of now, npm install
in a package directory (containing package.json
) will install devDependencies, whereas npm install -g
will not install them.
You can just say
callback();
Alternately you can use the call
method if you want to adjust the value of this
within the callback.
callback.call( newValueForThis);
Inside the function this
would be whatever newValueForThis
is.
What will be cleaner and easier to maintain?
All things being equal, probably JavaFX - the API is much more consistent across components. However, this depends much more on how the code is written rather than what library is used to write it.
And what will be faster to build from scratch?
Highly dependent on what you're building. Swing has more components around for it (3rd party as well as built in) and not all of them have made their way to the newer JavaFX platform yet, so there may be a certain amount of re-inventing the wheel if you need something a bit custom. On the other hand, if you want to do transitions / animations / video stuff then this is orders of magnitude easier in FX.
One other thing to bear in mind is (perhaps) look and feel. If you absolutely must have the default system look and feel, then JavaFX (at present) can't provide this. Not a big must have for me (I prefer the default FX look anyway) but I'm aware some policies mandate a restriction to system styles.
Personally, I see JavaFX as the "up and coming" UI library that's not quite there yet (but more than usable), and Swing as the borderline-legacy UI library that's fully featured and supported for the moment, but probably won't be so much in the years to come (and therefore chances are FX will overtake it at some point.)
This shows 1 to 20 numbers:
{% for i in "x"|rjust:"20"|make_list %}
{{ forloop.counter }}
{% endfor %}
also this can help you: (count_all_slider_objects come from views)
{% for i in "x"|rjust:count_all_slider_objects %}
{{ forloop.counter }}
{% endfor %}
or
{% with counter=count_all_slider_objects %}
{% if list_all_slider_objects %}
{% for slide in list_all_slider_objects %}
{{forloop.counter|add:"-1"}}
{% endfor%}
{% endif %}
{% endwith %}
Integer.valueOf()
returns an Integer object, while Integer.parseInt()
returns an int
primitive.
In SQL, the 'WHERE' and 'ON' clause,are kind of Conditional Statemants, but the major difference between them are, the 'Where' Clause is used in Select/Update Statements for specifying the Conditions, whereas the 'ON' Clause is used in Joins, where it verifies or checks if the Records are Matched in the target and source tables, before the Tables are Joined
For Example: - 'WHERE'
SELECT * FROM employee WHERE employee_id=101
For Example: - 'ON'
There are two tables employee and employee_details, the matching columns are employee_id.
SELECT * FROM employee
INNER JOIN employee_details
ON employee.employee_id = employee_details.employee_id
Hope I have answered your Question. Revert for any clarifications.
For anyone reading who wants ONLY the time in the output, you can pass options to JavaScript's Date::toLocaleString() method. Example:
var date = new Date("February 04, 2011 19:00:00");_x000D_
var options = {_x000D_
hour: 'numeric',_x000D_
minute: 'numeric',_x000D_
hour12: true_x000D_
};_x000D_
var timeString = date.toLocaleString('en-US', options);_x000D_
console.log(timeString);
_x000D_
timeString will be set to:
8:00 AM
Add "second: 'numeric'" to your options if you want seconds too. For all option see this.
we can use update for both insert and update/delte
Use the DateTime.ToUniversalTime
method.
You can use sys.platform
:
from sys import platform
if platform == "linux" or platform == "linux2":
# linux
elif platform == "darwin":
# OS X
elif platform == "win32":
# Windows...
sys.platform
has finer granularity than sys.name
.
For the valid values, consult the documentation.
See also the answer to “What OS am I running on?”
Maybe this is not the answer you needed, but I encountered similar problem, so I decided to put it here.
I needed to convert 500 xml files to UTF8 via Notepad++. Why Notepad++? When I used the option "Encode in UTF8" (many other converters use the same logic) it messed up all special characters, so I had to use "Convert to UTF8" explicitly.
Here some simple steps to convert multiple files via Notepad++ without messing up with special characters (for ex. diacritical marks).
convertToUTF8.py
import os
import sys
from Npp import notepad # import it first!
filePathSrc="C:\\Users\\" # Path to the folder with files to convert
for root, dirs, files in os.walk(filePathSrc):
for fn in files:
if fn[-4:] == '.xml': # Specify type of the files
notepad.open(root + "\\" + fn)
notepad.runMenuCommand("Encoding", "Convert to UTF-8")
# notepad.save()
# if you try to save/replace the file, an annoying confirmation window would popup.
notepad.saveAs("{}{}".format(fn[:-4], '_utf8.xml'))
notepad.close()
After all, run the script
First, we must make a distinction between layers and tiers. Layers are the way to logically break code into components and tiers are the physical nodes to place the components on. This question explains it better: What's the difference between "Layers" and "Tiers"?
A two layer architecture is usually just a presentation layer and data store layer. These can be on 1 tier (1 machine) or 2 tiers (2 machines) to achieve better performance by distributing the work load.
A three layer architecture usually puts something between the presentation and data store layers such as a business logic layer or service layer. Again, you can put this into 1,2, or 3 tiers depending on how much money you have for hardware and how much load you expect.
Putting multiple machines in a tier will help with the robustness of the system by providing redundancy.
Below is a good example of a layered architecture:
(source: microsoft.com)
A good reference for all of this can be found here on MSDN: http://msdn.microsoft.com/en-us/library/ms978678.aspx
In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:
http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/
Personally, when I have 3 or more cases, I usually just go with case/switch.
Don't use height property in input field.
Example:
.heighttext{
display:inline-block;
padding:15px 10px;
line-height:140%;
}
Always use padding and line-height css property. Its work perfect for all mobile device and all browser.
Try it once. after 1 hour of research on net I found Best Solution for this Problem.
Solution:- just add script
(function () {
// hold onto the drop down menu
var dropdownMenu;
// and when you show it, move it to the body
$(window).on('show.bs.dropdown', function (e) {
// grab the menu
dropdownMenu = $(e.target).find('.dropdown-menu');
// detach it and append it to the body
$('body').append(dropdownMenu.detach());
// grab the new offset position
var eOffset = $(e.target).offset();
// make sure to place it where it would normally go (this could be improved)
dropdownMenu.css({
'display': 'block',
'top': eOffset.top + $(e.target).outerHeight(),
'left': eOffset.left
});
});
// and when you hide it, reattach the drop down, and hide it normally
$(window).on('hide.bs.dropdown', function (e) {
$(e.target).append(dropdownMenu.detach());
dropdownMenu.hide();
});
})();
intList = Array.ConvertAll(stringList, int.Parse).ToList();
If you are changing route via Router Link Follow this:
constructor(public routerNavigate: Router){
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
this.router.navigated = false;
}
})
}
They sound about the same, however, the exit() also allows you to set the exit code of your PHP script.
Usually you don't really need this, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way.
Then you can use exit() and catch that later on. Die() however doesn't support that.
Die() always exists with code 0. So essentially a die() command does the following:
<?php
echo "I am going to die";
exit(0);
?>
Which is the same as:
<?php
die("I am going to die");
?>
I have come across this error when the app resides on a network share, and the device (laptop, tablet, ...) becomes disconnected from the network while the app is in use. In my case, it was due to a Surface tablet going out of wireless range. No problems after installing a better WAP.
The suggested regex will not validate the date, only the pattern.
So 99.99.9999 will pass the regex.
You later specified that you only need to validate the pattern but I still think it is more useful to create a date object
function isDate(str) { _x000D_
var parms = str.split(/[\.\-\/]/);_x000D_
var yyyy = parseInt(parms[2],10);_x000D_
var mm = parseInt(parms[1],10);_x000D_
var dd = parseInt(parms[0],10);_x000D_
var date = new Date(yyyy,mm-1,dd,0,0,0,0);_x000D_
return mm === (date.getMonth()+1) && dd === date.getDate() && yyyy === date.getFullYear();_x000D_
}_x000D_
var dates = [_x000D_
"13-09-2011", _x000D_
"13.09.2011",_x000D_
"13/09/2011",_x000D_
"08-08-1991",_x000D_
"29/02/2011"_x000D_
]_x000D_
_x000D_
for (var i=0;i<dates.length;i++) {_x000D_
console.log(dates[i]+':'+isDate(dates[i]));_x000D_
}
_x000D_
Here's a way to do it in Python without NumPy. Create a function that returns what you want and use a list comprehension, or the map function.
>>> a = [1, 2, 3, -4, 5]
>>> def zero_if_negative(x):
... if x < 0:
... return 0
... return x
...
>>> [zero_if_negative(x) for x in a]
[1, 2, 3, 0, 5]
>>> map(zero_if_negative, a)
[1, 2, 3, 0, 5]
For the sake of ease of use and understandability.
You can simply put a Tooltip anywhere on your form (from toolbox). You will then be given an options in the Properties of everything else in your form to determine what is displayed in that Tooltip (it reads something like "ToolTip on toolTip1"). Anytime you hover on an object, the text in that property will be displayed as a tooltip.
This does not cover custom on-the-fly tooltips like the original question is asking for. But I am leaving this here for others that do not need
I made this generic state machine out of Juliet's code. It's working awesome for me.
These are the benefits:
TState
and TCommand
, TransitionResult<TState>
to have more control over the output results of [Try]GetNext()
methodsStateTransition
only through AddTransition(TState, TCommand, TState)
making it easier to work with itCode:
public class StateMachine<TState, TCommand>
where TState : struct, IConvertible, IComparable
where TCommand : struct, IConvertible, IComparable
{
protected class StateTransition<TS, TC>
where TS : struct, IConvertible, IComparable
where TC : struct, IConvertible, IComparable
{
readonly TS CurrentState;
readonly TC Command;
public StateTransition(TS currentState, TC command)
{
if (!typeof(TS).IsEnum || !typeof(TC).IsEnum)
{
throw new ArgumentException("TS,TC must be an enumerated type");
}
CurrentState = currentState;
Command = command;
}
public override int GetHashCode()
{
return 17 + 31 * CurrentState.GetHashCode() + 31 * Command.GetHashCode();
}
public override bool Equals(object obj)
{
StateTransition<TS, TC> other = obj as StateTransition<TS, TC>;
return other != null
&& this.CurrentState.CompareTo(other.CurrentState) == 0
&& this.Command.CompareTo(other.Command) == 0;
}
}
private Dictionary<StateTransition<TState, TCommand>, TState> transitions;
public TState CurrentState { get; private set; }
protected StateMachine(TState initialState)
{
if (!typeof(TState).IsEnum || !typeof(TCommand).IsEnum)
{
throw new ArgumentException("TState,TCommand must be an enumerated type");
}
CurrentState = initialState;
transitions = new Dictionary<StateTransition<TState, TCommand>, TState>();
}
/// <summary>
/// Defines a new transition inside this state machine
/// </summary>
/// <param name="start">source state</param>
/// <param name="command">transition condition</param>
/// <param name="end">destination state</param>
protected void AddTransition(TState start, TCommand command, TState end)
{
transitions.Add(new StateTransition<TState, TCommand>(start, command), end);
}
public TransitionResult<TState> TryGetNext(TCommand command)
{
StateTransition<TState, TCommand> transition = new StateTransition<TState, TCommand>(CurrentState, command);
TState nextState;
if (transitions.TryGetValue(transition, out nextState))
return new TransitionResult<TState>(nextState, true);
else
return new TransitionResult<TState>(CurrentState, false);
}
public TransitionResult<TState> MoveNext(TCommand command)
{
var result = TryGetNext(command);
if(result.IsValid)
{
//changes state
CurrentState = result.NewState;
}
return result;
}
}
This is the return type of TryGetNext method:
public struct TransitionResult<TState>
{
public TransitionResult(TState newState, bool isValid)
{
NewState = newState;
IsValid = isValid;
}
public TState NewState;
public bool IsValid;
}
This is how you can create a OnlineDiscountStateMachine
from the generic class:
Define an enum OnlineDiscountState
for its states and an enum OnlineDiscountCommand
for its commands.
Define a class OnlineDiscountStateMachine
derived from the generic class using those two enums
Derive the constructor from base(OnlineDiscountState.InitialState)
so that the initial state is set to OnlineDiscountState.InitialState
Use AddTransition
as many times as needed
public class OnlineDiscountStateMachine : StateMachine<OnlineDiscountState, OnlineDiscountCommand>
{
public OnlineDiscountStateMachine() : base(OnlineDiscountState.Disconnected)
{
AddTransition(OnlineDiscountState.Disconnected, OnlineDiscountCommand.Connect, OnlineDiscountState.Connected);
AddTransition(OnlineDiscountState.Disconnected, OnlineDiscountCommand.Connect, OnlineDiscountState.Error_AuthenticationError);
AddTransition(OnlineDiscountState.Connected, OnlineDiscountCommand.Submit, OnlineDiscountState.WaitingForResponse);
AddTransition(OnlineDiscountState.WaitingForResponse, OnlineDiscountCommand.DataReceived, OnlineDiscountState.Disconnected);
}
}
use the derived state machine
odsm = new OnlineDiscountStateMachine();
public void Connect()
{
var result = odsm.TryGetNext(OnlineDiscountCommand.Connect);
//is result valid?
if (!result.IsValid)
//if this happens you need to add transitions to the state machine
//in this case result.NewState is the same as before
Console.WriteLine("cannot navigate from this state using OnlineDiscountCommand.Connect");
//the transition was successfull
//show messages for new states
else if(result.NewState == OnlineDiscountState.Error_AuthenticationError)
Console.WriteLine("invalid user/pass");
else if(result.NewState == OnlineDiscountState.Connected)
Console.WriteLine("Connected");
else
Console.WriteLine("not implemented transition result for " + result.NewState);
}
All these answers are great, but they all return you an empty string if the value is zero.
Try the following:
$v = 0;
$s = (string)$v ? (string)$v : "0";
I came across this, needing a solution which worked correctly and "nicely" on a variety of browsers, including Mobile Safari (iOS 9 at time of posting). None of the solutions were quite right. I offer the following (tested on Internet Explorer 11, Firefox, Chrome, and Safari):
history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event)
{
history.pushState(null, document.title, location.href);
});
Note the following:
history.forward()
(my old solution) does not work on Mobile Safari --- it seems to do nothing (i.e., the user can still go back). history.pushState()
does work on all of them.history.pushState()
is a url. Solutions which pass a string like 'no-back-button'
or 'pagename'
seem to work OK, until you then try a Refresh/Reload on the page, at which point a "Page not found" error is generated when the browser tries to locate a page with that as its URL. (The browser is also likely to include that string in the address bar when on the page, which is ugly.) location.href
should be used for the URL.history.pushState()
is a title. Looking around the web most places say it is "not used", and all the solutions here pass null
for that. However, in Mobile Safari at least, that puts the page's URL into the history dropdown the user can access. But when it adds an entry for a page visit normally, it puts in its title, which is preferable. So passing document.title
for that results in the same behaviour.Flexbox works.
.box{_x000D_
display: flex;_x000D_
flex-flow: row nowrap;_x000D_
justify-content: center;_x000D_
align-content: center;_x000D_
align-items:center;_x000D_
border:1px solid #e3f2fd;_x000D_
}_x000D_
.item{_x000D_
flex: 1 1 auto;_x000D_
border:1px solid #ffebee;_x000D_
}
_x000D_
<div class="box">_x000D_
<p class="item">A</p>_x000D_
<p class="item">B</p>_x000D_
<p class="item">C</p>_x000D_
</div>
_x000D_
Use:
"devDependencies": {
"@babel/core": "^7.2.0",
"@babel/preset-env": "^7.2.0",
"@babel/register": "^7.0.0"
}
{
"presets": ["@babel/preset-env"]
}
require("@babel/register")({})
// Import the rest of our application.
module.exports = require('./index.js')