No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
You are correct in that static files are copied to the application at link-time, and that shared files are just verified at link time and loaded at runtime.
The dlopen call is not only for shared objects, if the application wishes to do so at runtime on its behalf, otherwise the shared objects are loaded automatically when the application starts. DLLS and .so are the same thing. the dlopen exists to add even more fine-grained dynamic loading abilities for processes. You dont have to use dlopen yourself to open/use the DLLs, that happens too at application startup.
You have to use Javascript submit
function on your form
object. Take a look in other functions.
<form action="showMessage.jsp" method="post">
<a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
<input type="hidden" name="mess" value=<%=n%>/>
</form>
In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.
Anything you can do in regular old ANSI C can be done in Objective-C.
jQuery now supports .data();
, so if you have
<div id='author' data-content='stuff!'>
use
var author = $('#author').data("content"); // author = 'stuff!'
function DeletePersonel(id) { var data = new FormData(); data.append("__RequestVerificationToken", "@HtmlHelper.GetAntiForgeryToken()"); $.ajax({ type: 'POST', url: '/Personel/Delete/' + id, data: data, cache: false, processData: false, contentType: false, success: function (result) { } }); } public static class HtmlHelper { public static string GetAntiForgeryToken() { System.Text.RegularExpressions.Match value = System.Text.RegularExpressions.Regex.Match(System.Web.Helpers.AntiForgery.GetHtml().ToString(), "(?:value=\")(.*)(?:\")"); if (value.Success) { return value.Groups[1].Value; } return ""; } }
I was having a similar issue - like the original poster, I wanted to automate a file upload but I couldn't figure out how. Because this is on a register terminal at my family's store, I didn't want to install powershell (although that looks like an easy option), just wanted a simple .bat file to do this. This is pretty much what grawity and another user said; I'm new to this stuff, so here's a more detailed example and explanation (thanks also to http://www.howtogeek.com/howto/windows/how-to-automate-ftp-uploads-from-the-windows-command-line/ who explains how to do it with just one .bat file.)
Essentially you need 2 files - one .bat and one .txt. The .bat tells ftp.exe what switches to use. The .txt gives a list of commands to ftp.exe. In the text file put this:
username
password
cd whereverYouWantToPutTheFile
lcd whereverTheFileComesFrom
put C:\InventoryExport\inventory.test (or your file path)
bye
Save that wherever you want. In the BAT file put:
ftp.exe -s:C:\Windows\System32\test.txt destinationIP
pause
Obviously change the path after the -s: to wherever your text file is. Take out the pause when you're actually running it - it's just so you can see any errors. Of course, you can use "get" or any other ftp command in the .txt file to do whatever you need to do.
I'm not positive that you need the lcd command in the text file, like I said I'm new to using command line for this type of thing, but this is working for me.
supposing you have a function:
var fetchPage(page, callback) {
....
request(uri, function (error, response, body) {
....
if (something_good) {
callback(true, page+1);
} else {
callback(false);
}
.....
});
};
you can make use of callbacks like this:
fetchPage(1, x = function(next, page) {
if (next) {
console.log("^^^ CALLBACK --> fetchPage: " + page);
fetchPage(page, x);
}
});
global $DB;
$status = $DB->query("UPDATE exp_members SET group_id = '$group_id' WHERE member_id = '$member_id'");
if($status == false)
{
die("Didn't Update");
}
If you are using mysql_query
in the backend (whatever $DB->query()
uses to query the database), it will return a TRUE
or FALSE
for INSERT
, UPDATE
, and DELETE
(and a few others), commands, based on their status.
textBox1.Enabled = false;
"false" property will make the text box disable. and "true" will make it in regular form. Thanks.
UPDATE:
You'll also want to goto Security -> Server Roles
, and for public
check the permissions for TSQL Default TCP/TSQL Default VIA/TSQL Local Machine/TSQL Named Pipes
and remove the connect
permission
bool
exists in the current C - C99, but not in C89/90.
In C99 the native type is actually called _Bool
, while bool
is a standard library macro defined in stdbool.h
(which expectedly resolves to _Bool
). Objects of type _Bool
hold either 0 or 1, while true
and false
are also macros from stdbool.h
.
Note, BTW, that this implies that C preprocessor will interpret #if true
as #if 0
unless stdbool.h
is included. Meanwhile, C++ preprocessor is required to natively recognize true
as a language literal.
Here is an example:
List<String> names;
names.add("toto");
names.add("Lala");
names.add("papa");
int index = names.indexOf("papa"); // index = 2
SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.
As it happens, you are close. Just need leading+trailing wildcards and move the NOT
WHERE whatever NOT LIKE '%[a-z0-9]%'
Joao Costa answer also holds true for .Net core 2 projects.
launchsettings.json --> "launchBrowser": false
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": false,
"environmentVariables": {
"Hosting:Environment": "Development"
}
}
}
Did you init a local Git repository, into which this remote is supposed to be added?
Does your local directory have a .git
folder?
Try git init
.
I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:
from cx_Freeze import setup, Executable
import sys
productName = "ProductName"
if 'bdist_msi' in sys.argv:
sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName]
sys.argv += ['--install-script', 'install.py']
exe = Executable(
script="main.py",
base="Win32GUI",
targetName="Product.exe"
)
setup(
name="Product.exe",
version="1.0",
author="Me",
description="Copyright 2012",
executables=[exe],
scripts=[
'install.py'
]
)
Same solution as @Al3x for Windows x64, in cmd.exe
:
cd %programfiles%\Oracle\VirtualBox
VBoxManage internalcommands sethduuid "full/path/to/.vdi"
This randomizes the UUID of the disk. Pro tip: Right click the .vdi file while holding shift and select "Copy as path" to obtain "full/path/to/.vdi"
and enable quick edit in cmd.exe, then right click to paste.
myDropDown.Items.Remove(myDropDown.Items.FindByText("Chicago"));
You can also check Restlet which has full client-side capabilities, more REST oriented that lower-level libraries such as HttpURLConnection or Apache HTTP Client (which we can leverage as connectors).
Best regards, Jerome Louvel
I surveyed a few Excel modules for Python, and found openpyxl to be the best.
The free book Automate the Boring Stuff with Python has a chapter on openpyxl with more details or you can check the Read the Docs site. You won't need Office or Excel installed in order to use openpyxl.
Your program would look something like this:
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
stimulusTimes = [1, 2, 3]
reactionTimes = [2.3, 5.1, 7.0]
for i in range(len(stimulusTimes)):
sheet['A' + str(i + 6)].value = stimulusTimes[i]
sheet['B' + str(i + 6)].value = reactionTimes[i]
wb.save('example.xlsx')
NullPointerException
s are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.
Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerException
s is accidentally declaring an object with local scope when there is an instance variable with the same name.
In your case, the exception occurred in your constructor for Workshop on line 75. <init>
means the constructor for a class. If you look on that line in your code, you'll see the line
denimjeansButton.addItemListener(this);
There are fairly clearly two objects on this line: denimjeansButton
and this
. this
is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this
. denimjeansButton
is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton
or instantiate it.
What about putting the query results in an array, where you can do a count($array) and use the query resulting rows after? Example:
$sc='SELECT * FROM comments';
$res=array();
foreach($db->query($sc) as $row){
$res[]=$row;
}
echo "num rows: ".count($res);
echo "Select output:";
foreach($res as $row){ echo $row['comment'];}
Yes: implements Runnable
is the preferred way to do it, IMO. You're not really specialising the thread's behaviour. You're just giving it something to run. That means composition is the philosophically "purer" way to go.
In practical terms, it means you can implement Runnable
and extend from another class as well... and you can also implement Runnable
via a lambda expression as of Java 8.
I got same situation in one of my Ajax calls, where JSON
was throwing an error due to the newline in the Textarea field. The solution given here didn't worked for me.
So i used Javascript's .escape
function and it worked fine. Then to retrieve the value from JSON
, I just unescaped using .unescape
.
Alternatively, if you're just looking to play around with Javascript a nice in browser option is Codecademy's Javascript Lab.
They also have a Python and Ruby IDE.
In addition to what have been suggested, setdefault
might be useful in situations where you don't want to modify a value that has been already set. For example, when you have duplicate numbers and you want to treat them as one group. In this case, if you encounter a repeated duplicate
key which has been already set, you won't update the value of that key. You will keep the first encountered value. As if you are iterating/updating the repeated keys once only.
Here's a code example of recording the index for the keys/elements of a sorted list:
nums = [2,2,2,2,2]
d = {}
for idx, num in enumerate(sorted(nums)):
# This will be updated with the value/index of the of the last repeated key
# d[num] = idx # Result (sorted_indices): [4, 4, 4, 4, 4]
# In the case of setdefault, all encountered repeated keys won't update the key.
# However, only the first encountered key's index will be set
d.setdefault(num,idx) # Result (sorted_indices): [0, 0, 0, 0, 0]
sorted_indices = [d[i] for i in nums]
To show the "My Location" button you have to call
map.getUiSettings().setMyLocationButtonEnabled(true);
on your GoogleMap object.
textarea {
overflow-y: scroll; /* Vertical scrollbar */
overflow: scroll; /* Horizontal and vertical scrollbar*/
}
There is of course a lubridate
solution for this:
library(lubridate)
date <- "2009-10-01"
ymd(date) - 5
# [1] "2009-09-26"
is the same as
ymd(date) - days(5)
# [1] "2009-09-26"
Other time formats could be:
ymd(date) - months(5)
# [1] "2009-05-01"
ymd(date) - years(5)
# [1] "2004-10-01"
ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"
I don't know an easy method to convert a date object to any time zone, but if you want to convert it to the local time zone, you can just convert it with Date.prototype.getTime()
to the corresponding number of milliseconds, and back again.
date = new Date('2016-05-24T13:07:20');
date = new Date(date.getTime());
For example, date.getHours()
will now return 15
instead of 13
if you are, like me, in Austria (and it's summer).
I've read that the various datetime functions may exhibit non-standard behaviour in some browsers, so test this first. I can confirm that it works in Chrome.
Typically one would use an auxiliary numbers table you usually keep around for just this purpose with some variation on this:
SELECT *
FROM (
SELECT DATEADD(d, number - 1, '2009-01-01') AS dt
FROM Numbers
WHERE number BETWEEN 1 AND DATEDIFF(d, '2009-01-01', '2009-01-13') + 1
) AS DateRange
LEFT JOIN YourStuff
ON DateRange.dt = YourStuff.DateColumn
I've seen variations with table-valued functions, etc.
You can also keep a permanent list of dates. We have that in our data warehouse as well as a list of times of day.
` Please include either of these:
`#include<sstream>`
using std::istringstream;
put the following in ~/.gdbinit
define print_vector
if $argc == 2
set $elem = $arg0.size()
if $arg1 >= $arg0.size()
printf "Error, %s.size() = %d, printing last element:\n", "$arg0", $arg0.size()
set $elem = $arg1 -1
end
print *($arg0._M_impl._M_start + $elem)@1
else
print *($arg0._M_impl._M_start)@$arg0.size()
end
end
document print_vector
Display vector contents
Usage: print_vector VECTOR_NAME INDEX
VECTOR_NAME is the name of the vector
INDEX is an optional argument specifying the element to display
end
After restarting gdb (or sourcing ~/.gdbinit), show the associated help like this
gdb) help print_vector
Display vector contents
Usage: print_vector VECTOR_NAME INDEX
VECTOR_NAME is the name of the vector
INDEX is an optional argument specifying the element to display
Example usage:
(gdb) print_vector videoconfig_.entries 0
$32 = {{subChannelId = 177 '\261', sourceId = 0 '\000', hasH264PayloadInfo = false, bitrate = 0, payloadType = 68 'D', maxFs = 0, maxMbps = 0, maxFps = 134, encoder = 0 '\000', temporalLayers = 0 '\000'}}
I did in this way for myself, this helper method should come in handy for someone:
private static final int[] RES_IDS_ACTION_BAR_SIZE = {R.attr.actionBarSize};
/**
* Calculates the Action Bar height in pixels.
*/
public static int calculateActionBarSize(Context context) {
if (context == null) {
return 0;
}
Resources.Theme curTheme = context.getTheme();
if (curTheme == null) {
return 0;
}
TypedArray att = curTheme.obtainStyledAttributes(RES_IDS_ACTION_BAR_SIZE);
if (att == null) {
return 0;
}
float size = att.getDimension(0, 0);
att.recycle();
return (int) size;
}
You can commit some updated files, like this:
git commit file1 file2 file5 -m "commit message"
You can mock out aw.Clear
, either manually or using a testing framework like pymox. Manually, you'd do it using something like this:
class MyTest(TestCase):
def testClear():
old_clear = aw.Clear
clear_calls = 0
aw.Clear = lambda: clear_calls += 1
aps.Request('nv2', aw)
assert clear_calls == 1
aw.Clear = old_clear
Using pymox, you'd do it like this:
class MyTest(mox.MoxTestBase):
def testClear():
aw = self.m.CreateMock(aps.Request)
aw.Clear()
self.mox.ReplayAll()
aps.Request('nv2', aw)
Inside applicationContext.xml file of a maven Hibernet web app project below settings worked for me.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<jee:jndi-lookup id="dataSource"
jndi-name="Give_DataSource_Path_From_Your_Server"
expected-type="javax.sql.DataSource" />
Hope It will help someone.Thanks!
Reference of the de-referenced pointer is also same as the address of the pointed variable.
Explanation :-
int var = 3; int *p;
p = &var;
so, let's think address of var is : ABCDE
then,
p = ABCDE and &*p = ABCDE;
that means put &* together ,neutral the referencing and de-referencing.
also when declaring a function ,
the function's arguments should be the pointers,
and in the arguments of the this function when calling it in main method are should been with & operator.
it's bit confusing. But remember that int *p = &var; is also correct as the above pointer declaration.
$ git push origin develop:master
or, more generally
$ git push <remote> <local branch name>:<remote branch to push into>
DataFrame.compare
With pandas 1.1, you could essentially replicate Ted Petrou's output with a single function call. Example taken from the docs:
pd.__version__
# '1.1.0'
df1.compare(df2)
score isEnrolled Comment
self other self other self other
1 1.11 1.21 NaN NaN NaN NaN
2 NaN NaN 1.0 0.0 NaN On vacation
Here, "self" refers to the LHS dataFrame, while "other" is the RHS DataFrame. By default, equal values are replaced with NaNs so you can focus on just the diffs. If you want to show values that are equal as well, use
df1.compare(df2, keep_equal=True, keep_shape=True)
score isEnrolled Comment
self other self other self other
1 1.11 1.21 False False Graduated Graduated
2 4.12 4.12 True False NaN On vacation
You can also change the axis of comparison using align_axis
:
df1.compare(df2, align_axis='index')
score isEnrolled Comment
1 self 1.11 NaN NaN
other 1.21 NaN NaN
2 self NaN 1.0 NaN
other NaN 0.0 On vacation
This compares values row-wise, instead of column-wise.
:setlocal autoread
Auto reloads the current buffer..especially useful while viewing log files and it almost serves the functionality of "tail" program in unix from within vim.
Checking for compile errors from within vim. set the makeprg variable depending on the language let's say for perl
:setlocal makeprg = perl\ -c \ %
For PHP
set makeprg=php\ -l\ %
set errorformat=%m\ in\ %f\ on\ line\ %l
Issuing ":make" runs the associated makeprg and displays the compilation errors/warnings in quickfix window and can easily navigate to the corresponding line numbers.
Just use the following:
doublevalue+"";
This will work for any data type.
Example:
Double dd=10.09;
String ss=dd+"";
For next examples assumed that you use C++11. Example with ranged-based for loops:
for (auto &attack : m_attack) // access by reference to avoid copying
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
You should use const auto &attack
depending on the behavior of makeDamage()
.
You can use std::for_each
from standard library + lambdas:
std::for_each(m_attack.begin(), m_attack.end(),
[](Attack * attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
);
If you are uncomfortable using std::for_each
, you can loop over m_attack
using iterators:
for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
Use m_attack.cbegin()
and m_attack.cend()
to get const
iterators.
SELECT id, user_id, video_name
FROM sa_created_videos
ORDER BY LENGTH(id) ASC, LENGTH(user_id) DESC
This worked for me:
SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
Since the OP asked about CPU usage AND memory usage (accepted answer only shows technique to get cpu usage), I'd like to recommend the ActivityManager class and specifically the accepted answer from this question: How to get current memory usage in android?
@id/
and @android:id/
is not the same.
@id/
referencing ID in your application, @android:id/
referencing an item in Android platform.
Eclipse is wrong.
(ANSWER IS IN DOT NET 4.5 and in java, there must be a similar approach exist)
I am from West Bengal in INDIA.
As I understand your problem is ...
You want to produce similar to ' ? ' (It is a letter in Bengali language)
which has Unicode HEX : 0X0985
.
Now if you know this value in respect of your language then how will you produce that language specific Unicode symbol right ?
In Dot Net it is as simple as this :
int c = 0X0985;
string x = Char.ConvertFromUtf32(c);
Now x is your answer. But this is HEX by HEX convert and sentence to sentence conversion is a work for researchers :P
I had the same problem until I used a 3rd Party tool to generate the Class from the XSD and it worked! I discovered that the tool was adding some extra code at the top of my class. When I added this same code to the top of my original class it worked. Here's what I added...
#pragma warning disable
namespace MyNamespace
{
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.Xml;
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1064.2")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class MyClassName
{
...
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
When designing my app icons with Photoshop, I have found that no integer corner radius fits the device's mask exactly.
What I do now is create an empty project with Xcode, set a completely white PNG file as the icon, and turn off the preset bevel & gloss. Then, I run the app and take a screenshot of the home screen. Now, you can easily create a mask from that image, which you can use in Photoshop. This will get you perfectly rounded corners.
At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON
AJAX method because it easily returns JSONP using the ?callback=?
without having any issues with CORS.
data ='USER=<?echo trim($USER)?>' +
'&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();
//Call the REST program/method returns: JSONP
$.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
.done(function( json ) {
// loading...
if ($.trim(json.ERROR) != '') {
$("#error-msg").text(message).show();
}
else{
$(".error").hide();
$("#jsonp").text(json.whatever);
}
})
.fail(function( jqXHR, textStatus, error ) {
var err = textStatus + ", " + error;
alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
});
Generic array creation is disallowed in java but you can do it like
class Stack<T> {
private final T[] array;
public Stack(int capacity) {
array = (T[]) new Object[capacity];
}
}
For Fedora:
sudo yum install python-devel
sudo yum install libevent-devel
and finally:
sudo easy_install gevent
git diff filename
As DotNetMensch said but you DO NOT need to add another site in IIS as this can also cause further problems and make things more complicated because you then have a website within a website so the file paths, masterpage paths and web.config paths may need changing. You just need to edit teh bindings of the existing site and add the new subdomain there.
So:
Add sub-domain to DNS records. My host (RackSpace) uses a web portal to do this so you just log in and go to Network->Domains(DNS)->Actions->Create Zone, and enter your subdomain as mysubdomain.domain.com etc, leave the other settings as default
Go to your domain in IIS, right-click->Edit Bindings->Add, and add your new subdomain leaving everything else the same e.g. mysubdomain.domain.com
You may need to wait 5-10 mins for the DNS records to update but that's all you need.
Yahoo is very easy to use and provides customized data. Use the following page to learn more.
finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT=pder=.csv
WARNING - there are a few tutorials out there on the web that show you how to do this, but the region where you put in the stock symbols causes an error if you use it as posted. You will get a "MISSING FORMAT VALUE". The tutorials I found omits the commentary around GOOG.
Example URL for GOOG: http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,GOOG&f=nsl1op&e=.csv
When you add a jar file to a classpath you can attach a source directory or zip or jar file to that jar. In the Java Build Path properties, on the Libraries tab, expand the entry for the jar and you'll see there's an item for the source attachment. Select this item and then click the Edit button. This lets you select the folder, jar or zip that contains the source.
Additionally, if you select a class or a method in the jar and CTRL+CLICK on it (or press F3) then you'll go into the bytecode view which has an option to attach the source code.
Doing these things will give you all the parameter names as well as full javadoc.
If you don't have the source but do have the javadoc, you can attach the javadoc via the first method. It can even reference an external URL if you don't have it downloaded.
I usually read data by data reader this way. just added a small example.
string connectionString = "Data Source=DESKTOP-2EV7CF4;Initial Catalog=TestDB;User ID=sa;Password=tintin11#";
string queryString = "Select * from EMP";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
}
}
reader.Close();
}
}
Some answers does not explain the side effects of variations in the timezone for JavaScript Date object. So you should consider this answer if this is a concern for you.
Method 1: Machine's timezone dependent
By default, JavaScript returns a Date considering the machine's timezone, so getTime()
result varies from computer to computer. You can check this behavior running:
new Date(1970, 0, 1, 0, 0, 0, 0).getTime()
// Since 1970-01-01 is Epoch, you may expect ZERO
// but in fact the result varies based on computer's timezone
This is not a problem if you really want the time since Epoch considering your timezone. So if you want to get time since Epoch for the current Date or even a specified Date based on the computer's timezone, you're free to continue using this method.
// Seconds since Epoch (Unix timestamp format)
new Date().getTime() / 1000 // local Date/Time since Epoch in seconds
new Date(2020, 11, 1).getTime() / 1000 // time since Epoch to 2020-12-01 00:00 (local timezone) in seconds
// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)
new Date().getTime() // local Date/Time since Epoch in milliseconds
new Date(2020, 0, 2).getTime() // time since Epoch to 2020-01-02 00:00 (local timezone) in milliseconds
// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)
Method 2: Machine's timezone independent
However, if you want to get ride of variations in timezone and get time since Epoch for a specified Date in UTC (that is, timezone independent), you need to use Date.UTC
method or shift the date from your timezone to UTC:
Date.UTC(1970, 0, 1)
// should be ZERO in any computer, since it is ZERO the difference from Epoch
// Alternatively (if, for some reason, you do not want Date.UTC)
const timezone_diff = new Date(1970, 0, 1).getTime() // difference in milliseconds between your timezone and UTC
(new Date(1970, 0, 1).getTime() - timezone_diff)
// should be ZERO in any computer, since it is ZERO the difference from Epoch
So, using this method (or, alternatively, subtracting the difference), the result should be:
// Seconds since Epoch (Unix timestamp format)
Date.UTC(2020, 0, 1) / 1000 // time since Epoch to 2020-01-01 00:00 UTC in seconds
// Alternatively (if, for some reason, you do not want Date.UTC)
const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date(2020, 0, 1).getTime() - timezone_diff) / 1000 // time since Epoch to 2020-01-01 00:00 UTC in seconds
(new Date(2020, 11, 1).getTime() - timezone_diff) / 1000 // time since Epoch to 2020-12-01 00:00 UTC in seconds
// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)
Date.UTC(2020, 0, 2) // time since Epoch to 2020-01-02 00:00 UTC in milliseconds
// Alternatively (if, for some reason, you do not want Date.UTC)
const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date(2020, 0, 2).getTime() - timezone_diff) // time since Epoch to 2020-01-02 00:00 UTC in milliseconds
// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)
IMO, unless you know what you're doing (see note above), you should prefer Method 2, since it is machine independent.
End note
Although the recomendations in this answer, and since Date.UTC
does not work without a specified date/time, you may be inclined in using the alternative approach and doing something like this:
const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date().getTime() - timezone_diff) // <-- !!! new Date() without arguments
// means "local Date/Time subtracted by timezone since Epoch" (?)
This does not make any sense and it is probably WRONG (you are modifying the date). Be aware of not doing this. If you want to get time since Epoch from the current date AND TIME, you are most probably OK using Method 1.
Thread.start()
code registers the Thread with scheduler and the scheduler calls the run()
method. Also, Thread
is class while Runnable
is an interface.
Quick comparison of timings in response to the post by Abbafei:
import timeit
def func1():
phrase = 'Lucky Dog'
return any(i in 'LD' for i in phrase)
def func2():
phrase = 'Lucky Dog'
if ('L' in phrase) or ('D' in phrase):
return True
else:
return False
if __name__ == '__main__':
func1_time = timeit.timeit(func1, number=100000)
func2_time = timeit.timeit(func2, number=100000)
print('Func1 Time: {0}\nFunc2 Time: {1}'.format(func1_time, func2_time))
Output:
Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371
So the code is more compact with any, but faster with the conditional.
EDIT : TL;DR -- For long strings, if-then is still much faster than any!
I decided to compare the timing for a long random string based on some of the valid points raised in the comments:
# Tested in Python 2.7.14
import timeit
from string import ascii_letters
from random import choice
def create_random_string(length=1000):
random_list = [choice(ascii_letters) for x in range(length)]
return ''.join(random_list)
def function_using_any(phrase):
return any(i in 'LD' for i in phrase)
def function_using_if_then(phrase):
if ('L' in phrase) or ('D' in phrase):
return True
else:
return False
if __name__ == '__main__':
random_string = create_random_string(length=2000)
func1_time = timeit.timeit(stmt="function_using_any(random_string)",
setup="from __main__ import function_using_any, random_string",
number=200000)
func2_time = timeit.timeit(stmt="function_using_if_then(random_string)",
setup="from __main__ import function_using_if_then, random_string",
number=200000)
print('Time for function using any: {0}\nTime for function using if-then: {1}'.format(func1_time, func2_time))
Output:
Time for function using any: 0.1342546
Time for function using if-then: 0.0201827
If-then is almost an order of magnitude faster than any!
Facebook uses the LAMP stack, so if you want to get a career with them you're going to want to focus on that. In addition they often have C++ and/or Java listed in their requirements as well.
One of the postings includes the following requirements:
Another:
Another:
http://www.facebook.com/careers/#!/careers/department.php?dept=engineering
Also, do any other social networking sites use the same language?
Some other companys that use PHP/LAMP Stack:
I searched for any solution to not use the "SendKeys(CHR(13))
" methode I ever used to submit stuff in Browser. In this case I was happy to see your
InvokeMember("click")
but dont know why you know that you have to write "click" in there. Anyway Thanks
Use the same compiler options for linking also.
Example:
gcc -mfloat-abi=hard fpu=neon -c -o test.cpp test.o
gcc -mfloat-abi=hard fpu=neon -c test1.cpp test1.o
gcc test.o test1.o mfloat-abi=hard fpu=neon HardTest
i had a similar problem when i removed VS 2013 community Update 5 and switched over to VS 2015 community edition
and the problem acquired in windows phone 8.1 projects where it complained about not having the right msbuild toolset and about the emulators not installed even if they are.
i know that the source of the problem was the VS 2013 community settings that has been left by that last uninstall which messed everything for me even though the uninstall process went smooth with no problems from the control panel.
i did my best to remove any files left but there was always some thing left.
and what only fixed it for me is a fresh windows 10 x64 installation then after it i installed VS 2015 community edition and that's it!! no more errors for me and the wp8.1 emulator worked fine too!!
in my case now am completely sure that the previous visual studio install settings has messed everything for me and because there wasn't any way i found and tried to completely erase VS 2013 community files and settings i had to pay the price for it and reinstall my OS.
you might be able to avoid OS reinstall if you can find a way to completely erase last visual studio install files.
P.S:only attempt this solution(OS reinstall) after you tried every possible way first then if nothing works and only then ... make this solution as a last resort.
You might get a performance boost if you use parallel LINQ for multi cores. See Parallel LINQ (PLINQ) (MSDN).
If this happend to your XAMPP installation, just copy global_priv.MAD
and global_priv.MAI
files from ./xampp/mysql/backup/mysql/
to ./xampp/mysql/data/mysql/
.
In Bitbucket Server you can do a download by clicking on ...
next to the branch and then Download
For more info see Download an archive from Bitbucket Server
Iterate through the GridView rows and make the cells of your target columns invisible. In this example I want to keeps columns 4-6 visible as is, so we skip those:
foreach (GridViewRow row in yourGridView.Rows)
{
for (int i = 0; i < rows.Cells.Count; i++)
{
switch (i)
{
case 4:
case 5:
case 6:
continue;
}
row.Cells[i].Visible = false;
};
};
Then you will need to remove the column headers separately (keep in mind that removing header cells changes the length of the GridView after each removal):
grdReportRole.HeaderRow.Cells.RemoveAt(0);
You are calling nextInt
statically by using Random.nextInt
.
Instead, create a variable, Random r = new Random();
and then call r.nextInt(10)
.
It would be definitely worth while to check out:
You really should replace this line,
Random Random = new Random();
with something like this,
Random r = new Random();
If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.
They are exactly the same character. See: http://en.wikipedia.org/wiki/Dash
Barring browser bugs they will display the same in all cases, so the only difference would be concerning code readability, which would point to —
.
Or, if you are using UTF-8 as a charset in your HTML document, you could enter the character directly. That would also display exactly the same.
Edit 10th Dec 2015: As pointed out in the comments, ssi is deprecated since version 1.8. According to the documentation:
This tag has been deprecated and will be removed in Django 1.10. Use the include tag instead.
In my opinion, the right (best) answer to this question is the one from podshumok, as it explains why the behaviour of include when used along with inheritance.
However, I was somewhat surprised that nobody mentioned the ssi tag provided by the Django templating system, which is specifically designed for inline including an external piece of text. Here, inline means the external text will not be interpreted, parsed or interpolated, but simply "copied" inside the calling template.
Please, refer to the documentation for further details (be sure to check your appropriate version of Django in the selector at the lower right part of the page).
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#ssi
From the documentation:
ssi Outputs the contents of a given file into the page. Like a simple include tag, {% ssi %} includes the contents of another file – which must be specified using an absolute path – in the current page
Beware also of the security implications of this technique and also of the required ALLOWED_INCLUDE_ROOTS define, which must be added to your settings files.
Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?
Browsers might use the canPlayType
method internally to check if a <source>
is candidate to playback.
In Chrome, I have these results:
document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"
And for people who are looking for a jQuery compatible answer:
$('.foo:eq(1)').css('color', 'red');
HTML:
<div>
<div class="other"></div>
<div class="foo"></div>
<div class="foo">Find me</div>
...
Try this it worked for me
Write this in your Controller
public class DemoController: Controller
public async Task<FileStreamResult> GetLogoImage(string logoimage)
{
string str = "" ;
var filePath = Server.MapPath("~/App_Data/" + SubfolderName);//If subfolder exist otherwise leave.
// DirectoryInfo dir = new DirectoryInfo(filePath);
string[] filePaths = Directory.GetFiles(@filePath, "*.*");
foreach (var fileTemp in filePaths)
{
str= fileTemp.ToString();
}
return File(new MemoryStream(System.IO.File.ReadAllBytes(str)), System.Web.MimeMapping.GetMimeMapping(str), Path.GetFileName(str));
}
Here is my view
<div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
Please incre max_iter to 10000 as default value is 1000. Possibly, increasing no. of iterations will help algorithm to converge. For me it converged and solver was -'lbfgs'
log_reg = LogisticRegression(solver='lbfgs',class_weight='balanced', max_iter=10000)
We can use like below as well
SELECT *
FROM dbo.March2010 A
WHERE CAST(A.Date AS Date) >= '2017-03-22';
SELECT *
FROM dbo.March2010 A
WHERE CAST(A.Date AS Datetime) >= '2017-03-22 06:49:53.840';
In my case, the problem was that the phpMyAdmin version was specified wrongly in the phpmyadmin.conf
file. You may check that:
Go to wamp/apps/phpmyadmin3.x.x: notice the file name - what version you are currently using?
Open file wamp/alias/phpmyadmin.conf:
Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all
Check the first line (directory "c:/wamp/apps/phpmyadmin3.x.x/") is the file name exactly the same as your actual file name.
Make sure the directory file name is absolutely correct.
Use the following to delete all the tables in a linux environment.
hive -e 'show tables' | xargs -I '{}' hive -e 'drop table {}'
You should avoid using refs, you can do it with onChange
function.
On every change, update the state for the changed field.
Then you can easily check if that field is empty or whatever else you want.
You could do something as follows :
class Test extends React.Component {
constructor(props){
super(props);
this.state = {
fields: {},
errors: {}
}
}
handleValidation(){
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
//Name
if(!fields["name"]){
formIsValid = false;
errors["name"] = "Cannot be empty";
}
if(typeof fields["name"] !== "undefined"){
if(!fields["name"].match(/^[a-zA-Z]+$/)){
formIsValid = false;
errors["name"] = "Only letters";
}
}
//Email
if(!fields["email"]){
formIsValid = false;
errors["email"] = "Cannot be empty";
}
if(typeof fields["email"] !== "undefined"){
let lastAtPos = fields["email"].lastIndexOf('@');
let lastDotPos = fields["email"].lastIndexOf('.');
if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') == -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
formIsValid = false;
errors["email"] = "Email is not valid";
}
}
this.setState({errors: errors});
return formIsValid;
}
contactSubmit(e){
e.preventDefault();
if(this.handleValidation()){
alert("Form submitted");
}else{
alert("Form has errors.")
}
}
handleChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
render(){
return (
<div>
<form name="contactform" className="contactform" onSubmit= {this.contactSubmit.bind(this)}>
<div className="col-md-6">
<fieldset>
<input ref="name" type="text" size="30" placeholder="Name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
<span style={{color: "red"}}>{this.state.errors["name"]}</span>
<br/>
<input refs="email" type="text" size="30" placeholder="Email" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
<span style={{color: "red"}}>{this.state.errors["email"]}</span>
<br/>
<input refs="phone" type="text" size="30" placeholder="Phone" onChange={this.handleChange.bind(this, "phone")} value={this.state.fields["phone"]}/>
<br/>
<input refs="address" type="text" size="30" placeholder="Address" onChange={this.handleChange.bind(this, "address")} value={this.state.fields["address"]}/>
<br/>
</fieldset>
</div>
</form>
</div>
)
}
}
React.render(<Test />, document.getElementById('container'));
In this example I did the validation only for email and name, but you have an idea how to do it. For the rest you can do it self.
There is maybe a better way, but you will get the idea.
Hope this helps.
mvnrepository.com isn't a repository. It's a search engine. It might or might not tell you what repository it found stuff in if it's not central; since you didn't post an example, I can't help you read the output.
function functABC(){
// returns a promise that can be used later.
return $.ajax({
url: 'myPage.php',
data: {id: id}
});
}
functABC().then( response =>
console.log(response);
);
Nice read e.g. here.
This is not "synchronous" really, but I think it achieves what the OP intends.
async
option has since been deprecated):All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify
async: false
like described here
Note, however, that in most cases asynchronous execution (via callback on success) is just fine.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Text.RegularExpressions;
/// <summary>
/// Summary description for RegexUtilities
/// </summary>
public class RegexUtilities
{
bool InValid = false;
public bool IsValidEmail(string strIn)
{
InValid = false;
if (String.IsNullOrEmpty(strIn))
return false;
// Use IdnMapping class to convert Unicode domain names.
strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper);
if (InValid)
return false;
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
RegexOptions.IgnoreCase);
}
private string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try
{
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException)
{
InValid = true;
}
return match.Groups[1].Value + domainName;
}
}
RegexUtilities EmailRegex = new RegexUtilities();
if (txtEmail.Value != "")
{
string[] SplitClients_Email = txtEmail.Value.Split(',');
string Send_Email, Hold_Email;
Send_Email = Hold_Email = "";
int CountEmail;/**Region For Count Total Email**/
CountEmail = 0;/**First Time Email Counts Zero**/
bool EmaiValid = false;
Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();
if (SplitClients_Email[0].ToString() != "")
{
if (EmailRegex.IsValidEmail(Hold_Email))
{
Send_Email = Hold_Email;
CountEmail = 1;
EmaiValid = true;
}
else
{
EmaiValid = false;
}
}
if (EmaiValid == false)
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Enter A Valid Email ID.";
txtEmail.Focus();
txtEmail.Value = null;
ScriptManager.RegisterStartupScript(Page, this.GetType(), "SmoothScroll", "SmoothScroll();", true);
divStatusMsg.Visible = true;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "HideLabel();", true);
return false;
}
}
The most elegant way to find percentages across columns or index is to use pd.crosstab
.
Sample Data
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'office_id': list(range(1, 7)) * 2,
'sales': [np.random.randint(100000, 999999) for _ in range(12)]})
The output dataframe is like this
print(df)
state office_id sales
0 CA 1 764505
1 WA 2 313980
2 CO 3 558645
3 AZ 4 883433
4 CA 5 301244
5 WA 6 752009
6 CO 1 457208
7 AZ 2 259657
8 CA 3 584471
9 WA 4 122358
10 CO 5 721845
11 AZ 6 136928
Just specify the index, columns and the values to aggregate. The normalize keyword will calculate % across index or columns depending upon the context.
result = pd.crosstab(index=df['state'],
columns=df['office_id'],
values=df['sales'],
aggfunc='sum',
normalize='index').applymap('{:.2f}%'.format)
print(result)
office_id 1 2 3 4 5 6
state
AZ 0.00% 0.20% 0.00% 0.69% 0.00% 0.11%
CA 0.46% 0.00% 0.35% 0.00% 0.18% 0.00%
CO 0.26% 0.00% 0.32% 0.00% 0.42% 0.00%
WA 0.00% 0.26% 0.00% 0.10% 0.00% 0.63%
Of course you can write "something" a bit better to keep maintenance:
#include <iostream>
#include <cstdlib>
using namespace std;
class Something
{
public:
Something(int x, int y, int z) : a(x), b(y), c(z) { }
int a;
int b;
int c;
friend ostream& operator<<(ostream&, const Something&);
void print() const { printf("%i, %i, %i\n", a, b, c); }
};
ostream& operator<<(ostream& o, const Something& s)
{
o << s.a << ", " << s.b << ", " << s.c;
return o;
}
int main(void)
{
Something s(3, 2, 1);
// Output with printf
s.print(); // Simple as well, isn't it?
// Output with cout
cout << s << endl;
return 0;
}
And a bit extended test of cout vs. printf, added a test of 'double', if anyone wants to do more testing (Visual Studio 2008, release version of the executable):
#include <stdio.h>
#include <iostream>
#include <ctime>
class TimedSection {
char const *d_name;
//timespec d_start;
clock_t d_start;
public:
TimedSection(char const *name) :
d_name(name)
{
//clock_gettime(CLOCK_REALTIME, &d_start);
d_start = clock();
}
~TimedSection() {
clock_t end;
//clock_gettime(CLOCK_REALTIME, &end);
end = clock();
double duration = /*1e3 * (end.tv_sec - d_start.tv_sec) +
1e-6 * (end.tv_nsec - d_start.tv_nsec);
*/
(double) (end - d_start) / CLOCKS_PER_SEC;
std::cerr << d_name << '\t' << std::fixed << duration * 1000.0 << " ms\n";
}
};
int main() {
const int iters = 1000000;
char const *text = "01234567890123456789";
{
TimedSection s("cout with only endl");
for (int i = 0; i < iters; ++i)
std::cout << std::endl;
}
{
TimedSection s("cout with only '\\n'");
for (int i = 0; i < iters; ++i)
std::cout << '\n';
}
{
TimedSection s("printf with only '\\n'");
for (int i = 0; i < iters; ++i)
printf("\n");
}
{
TimedSection s("cout with string constant and endl");
for (int i = 0; i < iters; ++i)
std::cout << "01234567890123456789" << std::endl;
}
{
TimedSection s("cout with string constant and '\\n'");
for (int i = 0; i < iters; ++i)
std::cout << "01234567890123456789\n";
}
{
TimedSection s("printf with string constant and '\\n'");
for (int i = 0; i < iters; ++i)
printf("01234567890123456789\n");
}
{
TimedSection s("cout with some stuff and endl");
for (int i = 0; i < iters; ++i)
std::cout << text << "01234567890123456789" << i << std::endl;
}
{
TimedSection s("cout with some stuff and '\\n'");
for (int i = 0; i < iters; ++i)
std::cout << text << "01234567890123456789" << i << '\n';
}
{
TimedSection s("printf with some stuff and '\\n'");
for (int i = 0; i < iters; ++i)
printf("%s01234567890123456789%i\n", text, i);
}
{
TimedSection s("cout with formatted double (width & precision once)");
std::cout << std::fixed << std::scientific << std::right << std::showpoint;
std::cout.width(8);
for (int i = 0; i < iters; ++i)
std::cout << text << 8.315 << i << '\n';
}
{
TimedSection s("cout with formatted double (width & precision on each call)");
std::cout << std::fixed << std::scientific << std::right << std::showpoint;
for (int i = 0; i < iters; ++i)
{ std::cout.width(8);
std::cout.precision(3);
std::cout << text << 8.315 << i << '\n';
}
}
{
TimedSection s("printf with formatted double");
for (int i = 0; i < iters; ++i)
printf("%8.3f%i\n", 8.315, i);
}
}
The result is:
cout with only endl 6453.000000 ms
cout with only '\n' 125.000000 ms
printf with only '\n' 156.000000 ms
cout with string constant and endl 6937.000000 ms
cout with string constant and '\n' 1391.000000 ms
printf with string constant and '\n' 3391.000000 ms
cout with some stuff and endl 9672.000000 ms
cout with some stuff and '\n' 7296.000000 ms
printf with some stuff and '\n' 12235.000000 ms
cout with formatted double (width & precision once) 7906.000000 ms
cout with formatted double (width & precision on each call) 9141.000000 ms
printf with formatted double 3312.000000 ms
This code works for me:
public void Run()
{
Dog myDog = new Dog();
myDog.Name= "Foo";
myDog.Color = DogColor.Brown;
System.Console.WriteLine("{0}", myDog.ToString());
MemoryStream stream = SerializeToStream(myDog);
Dog newDog = (Dog)DeserializeFromStream(stream);
System.Console.WriteLine("{0}", newDog.ToString());
}
Where the types are like this:
[Serializable]
public enum DogColor
{
Brown,
Black,
Mottled
}
[Serializable]
public class Dog
{
public String Name
{
get; set;
}
public DogColor Color
{
get;set;
}
public override String ToString()
{
return String.Format("Dog: {0}/{1}", Name, Color);
}
}
and the utility methods are:
public static MemoryStream SerializeToStream(object o)
{
MemoryStream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, o);
return stream;
}
public static object DeserializeFromStream(MemoryStream stream)
{
IFormatter formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
object o = formatter.Deserialize(stream);
return o;
}
It is not possible to kill the session variable, when the machine unexpectly shutdown due to power failure. It is only possible when the user is idle for a long time or it is properly logout.
You can get posted form data from request.form
and query string data from request.args
.
myvar = request.form["myvar"]
myvar = request.args["myvar"]
In Kotlin you can use substringAfterLast
, specifying a delimiter.
val string = "/abc/def/ghfj.doc"
val result = url.substringAfterLast("/")
println(result)
// It will show ghfj.doc
From the doc:
Returns a substring after the last occurrence of delimiter. If the string does not contain the delimiter, returns missingDelimiterValue which defaults to the original string.
You can use Include Directives
<%
if(request.getParameter("p")!=null)
{
String p = request.getParameter("p");
%>
<%@include file="<%="includes/" + p +".jsp"%>"%>
<%
}
%>
or JSP Include Action
<%
if(request.getParameter("p")!=null)
{
String p = request.getParameter("p");
%>
<jsp:include page="<%="includes/"+p+".jsp"%>"/>
<%
}
%>
the different is include directive includes a file during the translation phase. while JSP Include Action includes a file at the time the page is requested
I recommend Spring MVC Framework as your controller to manipulate things. use url pattern instead of parameter.
example:
www.yourwebsite.com/products
instead of
www.yourwebsite.com/?p=products
Watch this video Spring MVC Framework
Something close to:
@Html.DropDownListFor(m => m.UserRole,
new SelectList(Model.Roles, "UserRoleId", "UserRole", Model.Roles.First().UserRoleId),
new { /* any html attributes here */ })
You need a SelectList to populate the DropDownListFor. For any HTML attributes you need, you can add:
new { @class = "DropDown", @id = "dropdownUserRole" }
If you are looking for a simple alternative, this can be done using a loop:
for i in $(find -name 'file_*' -follow -type f); do
zcat $i | agrep -dEOE 'grep'
done
or, more general and easy to understand form:
for i in $(YOUR_FIND_COMMAND); do
YOUR_EXEC_COMMAND_AND_PIPES
done
and replace any {} by $i in YOUR_EXEC_COMMAND_AND_PIPES
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
Your code could look more like:
<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
}
if($username !== 'admin')$userError = 'Invalid Username';
if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<style type='text.css'>
@import common.css;
</style>
</head>
<body>
<form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
<label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
<div class='error'><?php echo $userError;?></div>
<label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
<div class='error'><?php echo $passError;?></div>
<input type='submit' value='Home' name='sub' />
</form>
<script type='text/javascript' src='common.js'></script>
</body>
</html>
//gradle.properties
systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost
You have a couple of options:
Sub NumToText(ByRef sRng As String, Optional ByVal WS As Worksheet)
'---Converting visible range form Numbers to Text
Dim Temp As Double
Dim vRng As Range
Dim Cel As Object
If WS Is Nothing Then Set WS = ActiveSheet
Set vRng = WS.Range(sRng).SpecialCells(xlCellTypeVisible)
For Each Cel In vRng
If Not IsEmpty(Cel.Value) And IsNumeric(Cel.Value) Then
Temp = Cel.Value
Cel.ClearContents
Cel.NumberFormat = "@"
Cel.Value = CStr(Temp)
End If
Next Cel
End Sub
Sub Macro1()
Call NumToText("A2:A100", ActiveSheet)
End Sub
If you will still use JCrop, you will need only this php functions to crop the file:
$img_src = imagecreatefromjpeg($src);
$img_dest = imagecreatetruecolor($new_w,$new_h);
imagecopyresampled($img_dest,$img_src,0,0,$x,$y,$new_w,$new_h,$w,$h);
imagejpeg($img_dest,$dest);
client side:
jQuery(function($){
$('#target').Jcrop({
onChange: showCoords,
onSelect: showCoords,
onRelease: clearCoords
});
});
var x,y,w,h; //these variables are necessary to crop
function showCoords(c)
{
x = c.x;
y = c.y;
w = c.w;
h = c.h;
};
function clearCoords()
{
x=y=w=h=0;
}
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
I just want to add something to Willemoes answer. The same code written directly inside the HTML will look like this:
{{(FooController.results | filter : {id: 1})[0].name }}
Assuming that "results" is a variable of your FooController and you want to display the "name" property of the filtered item.
I'm still learning Android, so I cannot provide a rich context or reason for my suggestion, but this is what I am using to retrive files from both https and local urls. I am using this in my onActivity result (for both taking pictures and selecting from gallery), as well in an AsyncTask to retrieve the https urls.
InputStream input = new URL("your_url_string").openStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.
Cookies or URL parameters ( for ex. like http://example.com/myPage?asd=lol&boo=no ) are both suitable ways to transport data between 2 or more request. However they are not good in case you don't want that data to be readable/editable on client side.
The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.
Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.
In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.
Since pandas 1.0.0 df.sort_values
has a new parameter ignore_index
which does exactly what you need:
In [1]: df2 = df.sort_values(by=['x','y'],ignore_index=True)
In [2]: df2
Out[2]:
x y
0 0 0
1 0 1
2 0 2
3 1 0
4 1 1
5 1 2
6 2 0
7 2 1
8 2 2
You can use angular's function called angular.isUndefined(value)
returns boolean.
You may read more about angular's functions here: AngularJS Functions (isUndefined)
When running Wget with -r
or -p
, but without -N
, -nd
, or -nc
, re-downloading a file will result in the new copy simply overwriting the old.
So adding -nc
will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
Lets assume you want a data frame with the following schema:
root
|-- k: string (nullable = true)
|-- v: integer (nullable = false)
You simply define schema for a data frame and use empty RDD[Row]
:
import org.apache.spark.sql.types.{
StructType, StructField, StringType, IntegerType}
import org.apache.spark.sql.Row
val schema = StructType(
StructField("k", StringType, true) ::
StructField("v", IntegerType, false) :: Nil)
// Spark < 2.0
// sqlContext.createDataFrame(sc.emptyRDD[Row], schema)
spark.createDataFrame(sc.emptyRDD[Row], schema)
PySpark equivalent is almost identical:
from pyspark.sql.types import StructType, StructField, IntegerType, StringType
schema = StructType([
StructField("k", StringType(), True), StructField("v", IntegerType(), False)
])
# or df = sc.parallelize([]).toDF(schema)
# Spark < 2.0
# sqlContext.createDataFrame([], schema)
df = spark.createDataFrame([], schema)
Using implicit encoders (Scala only) with Product
types like Tuple
:
import spark.implicits._
Seq.empty[(String, Int)].toDF("k", "v")
or case class:
case class KV(k: String, v: Int)
Seq.empty[KV].toDF
or
spark.emptyDataset[KV].toDF
You can check out this method for sending image and form data altogether
<div class="form-group ml-5 mt-4" ng-app="myApp" ng-controller="myCtrl">
<label for="image_name">Image Name:</label>
<input type="text" placeholder="Image name" ng-model="fileName" class="form-control" required>
<br>
<br>
<input id="file_src" type="file" accept="image/jpeg" file-input="files" >
<br>
{{file_name}}
<img class="rounded mt-2 mb-2 " id="prvw_img" width="150" height="100" >
<hr>
<button class="btn btn-info" ng-click="uploadFile()">Upload</button>
<br>
<div ng-show = "IsVisible" class="alert alert-info w-100 shadow mt-2" role="alert">
<strong> {{response_msg}} </strong>
</div>
<div class="alert alert-danger " id="filealert"> <strong> File Size should be less than 4 MB </strong></div>
</div>
Angular JS Code
var app = angular.module("myApp", []);
app.directive("fileInput", function($parse){
return{
link: function($scope, element, attrs){
element.on("change", function(event){
var files = event.target.files;
$parse(attrs.fileInput).assign($scope, element[0].files);
$scope.$apply();
});
}
}
});
app.controller("myCtrl", function($scope, $http){
$scope.IsVisible = false;
$scope.uploadFile = function(){
var form_data = new FormData();
angular.forEach($scope.files, function(file){
form_data.append('file', file); //form file
form_data.append('file_Name',$scope.fileName); //form text data
});
$http.post('upload.php', form_data,
{
//'file_Name':$scope.file_name;
transformRequest: angular.identity,
headers: {'Content-Type': undefined,'Process-Data': false}
}).success(function(response){
$scope.IsVisible = $scope.IsVisible = true;
$scope.response_msg=response;
// alert(response);
// $scope.select();
});
}
});
It depends on what you're wanting to use it for. If you're just trying to save it, you should use pickle
(or, if you’re using CPython 2.x, cPickle
, which is faster).
>>> import pickle
>>> pickle.dumps({'foo': 'bar'})
b'\x80\x03}q\x00X\x03\x00\x00\x00fooq\x01X\x03\x00\x00\x00barq\x02s.'
>>> pickle.loads(_)
{'foo': 'bar'}
If you want it to be readable, you could use json
:
>>> import json
>>> json.dumps({'foo': 'bar'})
'{"foo": "bar"}'
>>> json.loads(_)
{'foo': 'bar'}
json
is, however, very limited in what it will support, while pickle
can be used for arbitrary objects (if it doesn't work automatically, the class can define __getstate__
to specify precisely how it should be pickled).
>>> pickle.dumps(object())
b'\x80\x03cbuiltins\nobject\nq\x00)\x81q\x01.'
>>> json.dumps(object())
Traceback (most recent call last):
...
TypeError: <object object at 0x7fa0348230c0> is not JSON serializable
use fwrite() instead of file_put_contents()
You could simply use ^[\w.]+
to match A-Z, a-z, 0-9 and _
It's good practice to give a parent to your QTimer
to use Qt's memory management system.
update()
is a QWidget function - is that what you are trying to call or not? http://qt-project.org/doc/qt-4.8/qwidget.html#update.
If number 2 does not apply, make sure that the function you are trying to trigger is declared as a slot in the header.
Finally if none of these are your issue, it would be helpful to know if you are getting any run-time connect errors.
I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.
scanf("%d %d %d", &var1, &var2, &var3);
Similarly if you want to read comma separated values use :
scanf("%d,%d,%d", &var1, &var2, &var3);
The solution to this, in .NET 4.5 is
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
If you don’t have .NET 4.5 then use
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
Similar to above, but I used (this was in CSHTML):
JavaScript:
var value = "Hello World!"<br>
$('.output').html(value);
CSHTML:
<div class="output"></div>
Its ok too:
h = 2
m = 7
s = 3
print("%02d:%02d:%02d" % (h, m, s))
so output will be: "02:07:03"
I would use regular expression matching to sum over variables with certain pattern names. For example:
df <- df %>% mutate(sum1 = rowSums(.[grep("x[3-5]", names(.))], na.rm = TRUE),
sum_all = rowSums(.[grep("x", names(.))], na.rm = TRUE))
This way you can create more than one variable as a sum of certain group of variables of your data frame.
In python 3.7 and above there is a new and easy way. here is the syntax:
name = "Eric"
age = 74
f"Hello, {name}. You are {age}."
OutPut:
Hello, Eric. You are 74.
pandoc
with browser
works well for me.
Usage: cat README.md | pandoc -f markdown_github | browser
Installation (Assuming you are using Mac OSX):
$ brew install pandoc
$ brew install browser
Or on Debian/Ubuntu: apt-get install pandoc browser
This misled me a bit - it should be setImageResource
instead of setBackgroundResource
:) !!
The following works fine :
ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);
btn.setImageResource(R.drawable.actions_record);
while when using the setBackgroundResource
the actual imagebutton's image
stays while the background image is changed which leads to a ugly looking imageButton object
Thanks.
The names and values are confusing. If you are looking for the total free memory you will have to calculate this value by your self. It is not what you get from freeMemory();
.
See the following guide:
Total designated memory, this will equal the configured -Xmx value:
Runtime.getRuntime().maxMemory();
Current allocated free memory, is the current allocated space ready for new objects. Caution this is not the total free available memory:
Runtime.getRuntime().freeMemory();
Total allocated memory, is the total allocated space reserved for the java process:
Runtime.getRuntime().totalMemory();
Used memory, has to be calculated:
usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
Total free memory, has to be calculated:
freeMemory = Runtime.getRuntime().maxMemory() - usedMemory;
A picture may help to clarify:
You can use attached properties for setting button border radius (also the same will work for textboxes).
Create class for attached property
public class CornerRadiusSetter
{
public static CornerRadius GetCornerRadius(DependencyObject obj) => (CornerRadius)obj.GetValue(CornerRadiusProperty);
public static void SetCornerRadius(DependencyObject obj, CornerRadius value) => obj.SetValue(CornerRadiusProperty, value);
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.RegisterAttached(nameof(Border.CornerRadius), typeof(CornerRadius),
typeof(CornerRadiusSetter), new UIPropertyMetadata(new CornerRadius(), CornerRadiusChangedCallback));
public static void CornerRadiusChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
{
Control control = sender as Control;
if (control == null) return;
control.Loaded -= Control_Loaded;
control.Loaded += Control_Loaded;
}
private static void Control_Loaded(object sender, EventArgs e)
{
Control control = sender as Control;
if (control == null || control.Template == null) return;
control.ApplyTemplate();
Border border = control.Template.FindName("border", control) as Border;
if (border == null) return;
border.CornerRadius = GetCornerRadius(control);
}
}
Then you can use attached property syntax for multiple buttons without style duplicates:
<Button local:CornerRadiusSetter.CornerRadius="10">Click me!</Button>
<Button local:CornerRadiusSetter.CornerRadius="5, 0, 0, 5">Click me!</Button>
<Button local:CornerRadiusSetter.CornerRadius="3, 20, 8, 15">Click me!</Button>
If you want to log to the same file:
command1 >> log_file 2>&1
If you want different files:
command1 >> log_file 2>> err_file
Please be carefull with the usage of autoSizeColumn()
. It can be used without problems on small files but please take care that the method is called only once (at the end) for each column and not called inside a loop which would make no sense.
Please avoid using autoSizeColumn()
on large Excel files. The method generates a performance problem.
We used it on a 110k rows/11 columns file. The method took ~6m to autosize all columns.
For more details have a look at: How to speed up autosizing columns in apache POI?
Since display
is not one of the animatable CSS properties.
One display:none
fadeOut animation replacement with pure CSS3 animations, just set width:0
and height:0
at last frame, and use animation-fill-mode: forwards
to keep width:0
and height:0
properties.
@-webkit-keyframes fadeOut {
0% { opacity: 1;}
99% { opacity: 0.01;width: 100%; height: 100%;}
100% { opacity: 0;width: 0; height: 0;}
}
@keyframes fadeOut {
0% { opacity: 1;}
99% { opacity: 0.01;width: 100%; height: 100%;}
100% { opacity: 0;width: 0; height: 0;}
}
.display-none.on{
display: block;
-webkit-animation: fadeOut 1s;
animation: fadeOut 1s;
animation-fill-mode: forwards;
}
Let take a string like :
XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
Note: Underscore ( _ ) is not considered a special character in this case.
/\bX\b/g
Should begin and end with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/\bX/g
Should begin with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/X\b/g
Should end with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/\BX\B/g
XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/\BX/g
Should not begin with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/X\B/g
Should not end with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/\bX\B/g
Should begin and not end with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/\BX\b/g
Should not begin and should end with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
This is not so much an answer to your original question as to one of the queries you had in the body of your question.
A little preamble, so that my naming doesn't seem strange:
import matplotlib
from matplotlib import rc
from matplotlib.figure import Figure
ax = self.figure.add_subplot( 111 )
As has been mentioned you can use ticklabel_format to specify that matplotlib should use scientific notation for large or small values:
ax.ticklabel_format(style='sci',scilimits=(-3,4),axis='both')
You can affect the way that this is displayed using the flags in rcParams (from matplotlib import rcParams) or by setting them directly. I haven't found a more elegant way of changing between '1e' and 'x10^' scientific notation than:
ax.xaxis.major.formatter._useMathText = True
This should give you the more Matlab-esc, and indeed arguably better appearance. I think the following should do the same:
rc('text', usetex=True)
You can do this with the aeimageresize jquery plugin.
https://plugins.jquery.com/ae.image.resize
https://github.com/adeelejaz/jquery-image-resize
$(function() {
$( ".resizeme" ).aeImageResize({ height: 250, width: 250 });
});
Add a line to your app.config in the configSections element
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0,
Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...
<log4net configSource="Config\Log4Net.config" />
In your application code, when you create the log, write
private static ILog GetLog(string logName)
{
ILog log = LogManager.GetLogger(logName);
return log;
}
If you want to prevent all caching (e.g. force a reload when using the back button) you need:
no-cache for IE
no-store for Firefox
There's my information about this here:
http://blog.httpwatch.com/2008/10/15/two-important-differences-between-firefox-and-ie-caching/
You just needed to update ca-certificates package. Before that just disable all repos with https that are failing. That's why solution with commenting mirrorlist or using http instead https would work also.
For example if you need to disable only epel repo:
yum --disablerepo=epel -y update ca-certificates
This will also help wget, curl, and anything else that uses SSL certificates.
I use .hpp because I want the user to differentiate what headers are C++ headers, and what headers are C headers.
This can be important when your project is using both C and C++ modules: Like someone else explained before me, you should do it very carefully, and its starts by the "contract" you offer through the extension
(Or .hxx, or .hh, or whatever)
This header is for C++ only.
If you're in a C module, don't even try to include it. You won't like it, because no effort is done to make it C-friendly (too much would be lost, like function overloading, namespaces, etc. etc.).
This header can be included by both a C source, and a C++ source, directly or indirectly.
It can included directly, being protected by the __cplusplus
macro:
extern "C"
.For example:
#ifndef MY_HEADER_H
#define MY_HEADER_H
#ifdef __cplusplus
extern "C"
{
#endif
void myCFunction() ;
#ifdef __cplusplus
} // extern "C"
#endif
#endif // MY_HEADER_H
Or it could be included indirectly by the corresponding .hpp header enclosing it with the extern "C"
declaration.
For example:
#ifndef MY_HEADER_HPP
#define MY_HEADER_HPP
extern "C"
{
#include "my_header.h"
}
#endif // MY_HEADER_HPP
and:
#ifndef MY_HEADER_H
#define MY_HEADER_H
void myCFunction() ;
#endif // MY_HEADER_H
the problem's actually caused by dependency. I spent whole the day to solve this prblm. Firstly, right click on project > Maven > add dependency
In "EnterGroupId, ArtifactId, or sha1...." box, type "org.springframework".
Then, from droped down list, expand "spring-web" list > Choose the newest version of jar file > Click OK.
Done!!!
I came across this answer trying to style the ReCaptcha v2 for a site that has a light and a dark mode. Played around some more and discovered that besides transform
, filter
is also applied to iframe
elements so ended up using the default/light ReCaptcha and doing this when the user is in dark mode:
.g-recaptcha {
filter: invert(1) hue-rotate(180deg);
}
The hue-rotate(180deg)
makes it so that the logo is still blue and the check-mark is still green when the user clicks it, while keeping white invert()
'ed to black and vice versa.
Didn't see this in any answer or comment so decided to share even if this is an old thread.
This happened to me on Windows 7 and VS 2013 while viewing a project on the browser after build. I only had to close the browser "Chrome" then made sure that the port is not in use in my Network Activities using some utility then tried again and worked without any problem.
Regarding the upvoted answer, I liked it except that if the resulting "listfiles" array is used in an array formula {CSE}, the list values come out all in a horizontal row. To make them come out in a vertical column, I simply made the array two dimensional as follows:
ReDim vaArray(1 To oFiles.Count, 0)
i = 1
For Each oFile In oFiles
vaArray(i, 0) = oFile.Name
i = i + 1
Next
First you need to publish the file by:
BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go.
Save your file to a particular folder.
Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug
folder below the project file (.csproj).
In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files.
(You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)
NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
A functional approach to replacing an element of an array in javascript:
const replace = (array, index, ...items) => [...array.slice(0, index), ...items, ...array.slice(index + 1)];
_x000D_
mongod
wasn't working to start the daemon for me but after I ran the following, it started working:
'mongod --fork --logpath /var/log/mongodb.log'
(from here: https://docs.mongodb.com/manual/tutorial/manage-mongodb-processes/)
OK, as others note, the best thing to do is to use java.util.concurrent
package. I highly recommend "Java Concurrency in Practice". It's a great book that covers almost everything you need to know.
As for your particular implementation, as I noted in the comments, don't start Threads from Constructors -- it can be unsafe.
Leaving that aside, the second implementation seem better. You don't want to put queues in static fields. You are probably just loosing flexibility for nothing.
If you want to go ahead with your own implementation (for learning purpose I guess?), supply a start()
method at least. You should construct the object (you can instantiate the Thread
object), and then call start()
to start the thread.
Edit: ExecutorService
have their own queue so this can be confusing.. Here's something to get you started.
public class Main {
public static void main(String[] args) {
//The numbers are just silly tune parameters. Refer to the API.
//The important thing is, we are passing a bounded queue.
ExecutorService consumer = new ThreadPoolExecutor(1,4,30,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(100));
//No need to bound the queue for this executor.
//Use utility method instead of the complicated Constructor.
ExecutorService producer = Executors.newSingleThreadExecutor();
Runnable produce = new Produce(consumer);
producer.submit(produce);
}
}
class Produce implements Runnable {
private final ExecutorService consumer;
public Produce(ExecutorService consumer) {
this.consumer = consumer;
}
@Override
public void run() {
Pancake cake = Pan.cook();
Runnable consume = new Consume(cake);
consumer.submit(consume);
}
}
class Consume implements Runnable {
private final Pancake cake;
public Consume(Pancake cake){
this.cake = cake;
}
@Override
public void run() {
cake.eat();
}
}
Further EDIT:
For producer, instead of while(true)
, you can do something like:
@Override
public void run(){
while(!Thread.currentThread().isInterrupted()){
//do stuff
}
}
This way you can shutdown the executor by calling .shutdownNow()
. If you'd use while(true)
, it won't shutdown.
Also note that the Producer
is still vulnerable to RuntimeExceptions
(i.e. one RuntimeException
will halt the processing)
public class MenuTest extends Activity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.more_tab_menu, menu);
// return true so that the menu pop up is opened
return true;
}
}
and don't forget to press the menu button or icon on Emulator or device
You can do it like this:
SELECT * FROM ... WHERE name LIKE 'someone'
(It's not the solution, but in some cases is very convenient)
"The LIKE operator does a pattern matching comparison. The operand to the right contains the pattern, the left hand operand contains the string to match against the pattern. A percent symbol ("%") in the pattern matches any sequence of zero or more characters in the string. An underscore ("_") in the pattern matches any single character in the string. Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching). (A bug: SQLite only understands upper/lower case for ASCII characters. The LIKE operator is case sensitive for unicode characters that are beyond the ASCII range. For example, the expression 'a' LIKE 'A' is TRUE but 'æ' LIKE 'Æ' is FALSE.)."
I Have a Query With This result :
SELECT Top 3
id,
Paytype
FROM dbo.OrderExpresses
WHERE CreateDate > '2018-04-08'
The Result is :
22082 1
22083 2
22084 1
I Want Change The Code To String In Query, So I Use This Code :
SELECT TOP 3
id,
CASE WHEN Paytype = 1 THEN N'Credit' ELSE N'Cash' END AS PayTypeString
FROM dbo.OrderExpresses
WHERE CreateDate > '2018-04-08'
And Result Is :)
22082 Credit
22083 Cash
22084 Credit
To do this, you don't really even need Javascript if you're going to use
$('#test').css('text-transform', 'capitalize');
Why not do this as CSS like
#test,h1,h2,h3 { text-transform: capitalize; }
or do it as a class and apply that class to wherever you need it
.ucwords { text-transform: capitalize; }
Filippo Valsorda wrote a cross-platform tool, mkcert
, to do this for lots of trust stores. I presume he wrote it for the same reason that there are so many answers to this question: it is a pain to do the "right" thing for SubjectAltName
certificates signed by a trusted root CA.
mkcert
is included in the major package management systems for Windows, macOS, and several Linux flavors. It is also mentioned in the Chromium docs in Step 4 of Testing Powerful Features.
mkcert
mkcert
is a simple tool for making locally-trusted development certificates. It requires no configuration.$ mkcert -install Created a new local CA at "/Users/filippo/Library/Application Support/mkcert" The local CA is now installed in the system trust store! ?? The local CA is now installed in the Firefox trust store (requires browser restart)! $ mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1 Using the local CA at "/Users/filippo/Library/Application Support/mkcert" ? Created a new certificate valid for the following names - "example.com" - "*.example.com" - "example.test" - "localhost" - "127.0.0.1" - "::1" The certificate is at "./example.com+5.pem" and the key at "./example.com+5-key.pem" ?
This doesn't use sed, but using >> will append to a file. For example:
echo 'one, two, three' >> testfile.csv
Edit: To prepend to a file, try something like this:
echo "text"|cat - yourfile > /tmp/out && mv /tmp/out yourfile
I found this through a quick Google search.
Simply remove the .value
from your code.
Set envFrmwrkPath = ActiveSheet.Range("D6").Value
instead of this, use:
Set envFrmwrkPath = ActiveSheet.Range("D6")
On Mac OSX 10.15, Even after installing gpg, i was getting gpg2 command not found
$ brew install gnupg gnupg2
Warning: gnupg 2.2.23 is already installed and up-to-date
To reinstall 2.2.23, run `brew reinstall gnupg`
$ gpg2 --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
-bash: gpg2: command not found
Instead, this worked for me
$ gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
You can read about it here.
return render_template('page.html'), 201
In Bootstrap 3 (3.0.3) adding the "text-center"
class to a td
element works out of the box.
I.e., the following centers some text
in a table cell:
<td class="text-center">some text</td>
window.open('your_url', 'popup_name','height=' + screen.height + ',width=' + screen.width + ',resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes')
Windows 7 64-bit, with both Python3.4 and Python2.7 installed at some point :)
I'm using Py.exe to route to Py2 or Py3 depending on the script's needs - but I previously improperly uninstalled Python27 before.
Py27 was removed manually from C:\python\Python27 (the folder Python27 was deleted by me previously)
Upon re-installing Python27, it gave the above error you specify.
It would always back out while trying to 'remove shortcuts' during the installation process.
I placed a copy of Python27 back in that original folder, at C:\Python\Python27, and re-ran the same failing Python27 installer. It was happy locating those items and removing them, and proceeded with the install.
This is not the answer that addresses registry key issues (others mention that) but it is somewhat of a workaround if you know of previous installations that were improperly removed.
You could have some insight to this by opening "regedit" and searching for "Python27" - a registry key appeared in my command-shell Cache pointing at c:\python\python27\ (which had been removed and was not present when searching in the registry upon finding it).
That may help point to previously improperly removed installations.
Good luck!
Cloudera and Hortonworks are the best tools to start up with the HDFS in Microsoft Windows. You can also use VMWare or VBox to initiate Virtual Machine to establish build to your HDFS and Spark, Hive, HBase, Pig, Hadoop with Scala, R, Java, Python.
It might be interesting to some of you that in case of multiple default parameters:
void printValues(int x=10, int y=20, int z=30)
{
std::cout << "Values: " << x << " " << y << " " << z << '\n';
}
Given the following function calls:
printValues(1, 2, 3);
printValues(1, 2);
printValues(1);
printValues();
The following output is produced:
Values: 1 2 3
Values: 1 2 30
Values: 1 20 30
Values: 10 20 30
Reference: http://www.learncpp.com/cpp-tutorial/77-default-parameters/
// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag
---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';
@Directive({
selector: '[resize]',
host: { '(window:resize)': 'onResize()' } // Window resize listener
})
export class AutoResize {
element: ElementRef; // Element that associated to attribute.
$window: any;
constructor(_element: ElementRef) {
this.element = _element;
// Get instance of DOM window.
this.$window = angular.element(window);
this.onResize();
}
// Adjust height of element.
onResize() {
$(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
}
}
You can use new Date().getTime()
for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms
into s
.
const start = new Date().getTime();
const end = new Date().getTime();
const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);
you can create your own custom event by using diagnostics.Event log class. Open a windows application and on a button click do the following code.
System.Diagnostics.EventLog.CreateEventSource("ApplicationName", "MyNewLog");
"MyNewLog" means the name you want to give to your log in event viewer.
for more information check this link [ http://msdn.microsoft.com/en-in/library/49dwckkz%28v=vs.90%29.aspx]
None of the other answers worked for me. The solution that worked for me was to download the missing artifact manually via cmd:
mvn dependency:get -DrepoUrl=http://repo.maven.apache.org/maven2/ -Dartifact=ro.isdc.wro4j:wro4j-maven-plugin:1.8.0
After this change need to let know the Idea about new available artifacts. This can be done in "Settings > Maven > Repositories", select there your "Local" and simply click "Update".
Edit: the -DrepoUrl seems to be deprecated. -DremoteRepositories should be used instead. Source: Apache Maven Dependency Plugin – dependency:get.
It should be pretty obvious from your question that you're actually just asking about the difference between git merge
and git rebase
.
So let's suppose you're in the common case - you've done some work on your master branch, and you pull from origin's, which also has done some work. After the fetch, things look like this:
- o - o - o - H - A - B - C (master)
\
P - Q - R (origin/master)
If you merge at this point (the default behavior of git pull), assuming there aren't any conflicts, you end up with this:
- o - o - o - H - A - B - C - X (master)
\ /
P - Q - R --- (origin/master)
If on the other hand you did the appropriate rebase, you'd end up with this:
- o - o - o - H - P - Q - R - A' - B' - C' (master)
|
(origin/master)
The content of your work tree should end up the same in both cases; you've just created a different history leading up to it. The rebase rewrites your history, making it look as if you had committed on top of origin's new master branch (R
), instead of where you originally committed (H
). You should never use the rebase approach if someone else has already pulled from your master branch.
Finally, note that you can actually set up git pull
for a given branch to use rebase instead of merge by setting the config parameter branch.<name>.rebase
to true. You can also do this for a single pull using git pull --rebase
.
On your list view, use setOnItemClickListener
Yes, you may use both ways. If you just want to separate the elements and show they in separated lines, a list is simpler:
set list=A B C D
A list of values separated by space may be easily processed by for
command:
(for %%a in (%list%) do (
echo %%a
echo/
)) > theFile.txt
You may also create an array this way:
setlocal EnableDelayedExpansion
set n=0
for %%a in (A B C D) do (
set vector[!n!]=%%a
set /A n+=1
)
and show the array elements this way:
(for /L %%i in (0,1,3) do (
echo !vector[%%i]!
echo/
)) > theFile.txt
For further details about array management in Batch files, see: Arrays, linked lists and other data structures in cmd.exe (batch) script
ATTENTION! You must know that all characters included in set
command are inserted in the variable name (at left of equal sign), or in the variable value. For example, this command:
set list = "A B C D"
create a variable called list
(list-space) with the value "A B C D"
(space, quote, A, etc). For this reason, it is a good idea to never insert spaces in set
commands. If you need to enclose the value in quotes, you must enclose both the variable name and its value:
set "list=A B C D"
PS - You should NOT use ECHO.
in order to left blank lines! An alternative is ECHO/
. For further details about this point, see: http://www.dostips.com/forum/viewtopic.php?f=3&t=774
No, but you can with an if
-else if
-else
chain which achieves the same result:
if (answer >= 1 && answer <= 4)
cout << "You need more cars.";
else if (answer <= 8)
cout << "Now you need a house.";
else
cout << "What are you? A peace-loving hippie freak?";
You may also want to handle the case of 0 cars and then also the unexpected case of a negative number of cars probably by throwing an exception.
PS: I've renamed Answer
to answer
as it's considered bad style to start variables with an uppercase letter.
As a side note, scripting languages such as Python allow for the nice if answer in [1, 2, 3, 4]
syntax which is a flexible way of achieving what you want.
Here's how you can do that.
Writing the persistent cookie.
//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");
//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());
//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);
//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);
Reading the persistent cookie.
//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
//No cookie found or cookie expired.
//Handle the situation here, Redirect the user or simply return;
}
//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
string userId = myCookie.Values["userid"].ToString();
//Yes userId is found. Mission accomplished.
}
Use a negative lookahead and a negative lookbehind:
> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']
In other words, you always split by \s
(whitespace), and only split by commas and periods if they are not followed (?!\d)
or preceded (?<!\d)
by a digit.
DEMO.
EDIT: As per @verdesmarald comment, you may want to use the following instead:
> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']
This will split "1.2,a,5"
into ["1.2", "a", "5"]
.
DEMO.
to_char(timestamp, 'YYYY-MM')
You say that the order is not "right", but I cannot see why it is wrong (at least until year 10000 comes around).
This post is old and probably solved but I had the same issue. I resolved it by creating a view of the original table specifying the new column order.
From here I could either use the view or create a new table from the view.
CREATE VIEW original_tab_vw AS SELECT a.col1, a.col3, a.col4, a.col2 FROM original_tab a WHERE a.col1 IS NOT NULL --or whatever
SELECT * INTO new_table FROM original_tab_vw
Rename or drop the original table and set the name of the new table to the old table.
I know this question is several years old but I'd like to provide an answer to this explaining why rather than how
Purpose of Primary Key: To identify a row in a database uniquely => A row represents a single instance of the entity type modeled by the table. A primary key enforces integrity of an entity, AKA Entity Integrity. Primary Key would be a clustered index i.e. it defines the order in which data is physically stored in a table.
Purpose of Unique Key: Ok, with the Primary Key we have a way to uniquely identify a row. But I have a business need such that, another column/a set of columns should have unique values. Well, technically, given that this column(s) is unique, it can be a candidate to enforce entity integrity. But for all we know, this column can contain data originating from an external organization that I may have a doubt about being unique. I may not trust it to provide entity integrity. I just make it a unique key to fulfill my business requirement.
There you go!
If JDK installed but still not working.
In Eclipse follow below steps:- Window --> Preference --> Installed JREs -->Change path of JRE to JDK(add).
After a bit of time (and more searching), I found this blog entry by Jomo Fisher.
One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:
Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
[Snip]
The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup>
So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy
attribute reverts back to CLR 2.0 loading.
This is not a bug in either implementation. There is no requirement to escape U+00B0. To quote the RFC:
2.5. Strings
The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).
Any character may be escaped.
Escaping everything inflates the size of the data (all code points can be represented in four or fewer bytes in all Unicode transformation formats; whereas encoding them all makes them six or twelve bytes).
It is more likely that you have a text transcoding bug somewhere in your code and escaping everything in the ASCII subset masks the problem. It is a requirement of the JSON spec that all data use a Unicode encoding.
The other answers answer your question. Another important thing to know about names in Python is that they are either local or global on a per-scope basis.
Consider this, for example:
value = 42
def doit():
print value
value = 0
doit()
print value
You can probably guess that the value = 0
statement will be assigning to a local variable and not affect the value of the same variable declared outside the doit()
function. You may be more surprised to discover that the code above won't run. The statement print value
inside the function produces an UnboundLocalError.
The reason is that Python has noticed that, elsewhere in the function, you assign the name value
, and also value
is nowhere declared global
. That makes it a local variable. But when you try to print it, the local name hasn't been defined yet. Python in this case does not fall back to looking for the name as a global variable, as some other languages do. Essentially, you cannot access a global variable if you have defined a local variable of the same name anywhere in the function.
A simple example: We have the following array
li = [{"id":1,"name":"ronaldo"},{"id":2,"name":"messi"}]
Now, we want to find the object in the array that has id equal to 1
next
with list comprehensionnext(x for x in li if x["id"] == 1 )
[x for x in li if x["id"] == 1 ][0]
def find(arr , id):
for x in arr:
if x["id"] == id:
return x
find(li , 1)
Output all the above methods is {'id': 1, 'name': 'ronaldo'}
Swift 4.1 introduces new -Osize
optimization mode.
In Swift 4.1 the compiler now supports a new optimization mode which enables dedicated optimizations to reduce code size.
The Swift compiler comes with powerful optimizations. When compiling with -O the compiler tries to transform the code so that it executes with maximum performance. However, this improvement in runtime performance can sometimes come with a tradeoff of increased code size. With the new -Osize optimization mode the user has the choice to compile for minimal code size rather than for maximum speed.
To enable the size optimization mode on the command line, use -Osize instead of -O.
Further reading : https://swift.org/blog/osize/
There's so much confusion around this subject, and none of the existing answers cover everything clearly and directly. Here are some examples with comments inline.
//this is a declaration
var foo;
//this is an assignment
bar = 3;
//this is a declaration and an assignment
var dual = 5;
A declaration sets a DontDelete flag. An assignment does not.
A declaration ties that variable to the current scope.
A variable assigned but not declared will look for a scope to attach itself to. That means it will traverse up the food-chain of scope until a variable with the same name is found. If none is found, it will be attached to the top-level scope (which is commonly referred to as global).
function example(){
//is a member of the scope defined by the function example
var foo;
//this function is also part of the scope of the function example
var bar = function(){
foo = 12; // traverses scope and assigns example.foo to 12
}
}
function something_different(){
foo = 15; // traverses scope and assigns global.foo to 15
}
For a very clear description of what is happening, this analysis of the delete function covers variable instantiation and assignment extensively.
You can put an image into ::before pseudoelement and set the same dimensions for as is the image + add overflow:hidden, like:
li a::before{
content:url('img');
width:20px;
height:10px
}
a {
overflow:hidden;
width:20px;
height:10px
}
From MSDN:
A
String
object is a sequential collection ofSystem.Char
objects that represent a string.
So you can use this:
var howManyBytes = yourString.Length * sizeof(Char);
The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
The code above depends on the nuget package RestSharp, which you can easily install.
Have you tried JQuery? Vanilla javascript can be tough. Try using this:
$('.container-element').add('<div>Insert Div Content</div>');
.container-element
is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add()
function inserts HTML into the container-element.
#include <iostream>
int main(){
int rows=4;
int cols=4;
int **arr;
arr = new int*[rows];
for(int i=0;i<rows;i++){
arr[i]=new int[cols];
}
// statements
for(int i=0;i<rows;i++){
delete []arr[i];
}
delete []arr;
return 0;
}
<Prefix>
&
for killing a window
<Prefix>
x
for killing a pane
If there is only one pane (i.e. the window is not split into multiple panes, <Prefix>
x
would kill the window)
As always iterated, <Prefix>
is generally CTRL+b
. (I think for beginner questions, we can just say CTRL+b
all the time, and not talk about prefix at all, but anyway :) )
You can use window.scrollTo()
, like this:
window.scrollTo(0, 0); // values are x,y-offset
You need to set the password for root@localhost
to be blank. There are two ways:
The MySQL SET PASSWORD
command:
SET PASSWORD FOR root@localhost=PASSWORD('');
Using the command-line mysqladmin
tool:
mysqladmin -u root -pType_in_your_current_password_here password ''
I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>
). It seems that when you inspect the element with Developer Tools, the element.style
has no style assigned. So instead of using ng-class
, I have tried using ng-style
, and in this case, the new CSS attribute does appear inside element.style
. This code works great for me:
<tr ng-repeat="element in collection">
[...amazing code...]
<td ng-style="myvar === 0 && {'background-color': 'red'} ||
myvar === 1 && {'background-color': 'green'} ||
myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>
[...more amazing code...]
</tr>
Myvar is what I am evaluating, and in each case I apply a style to each <td>
depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.
UPDATE
If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:
<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">
Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a
OR we are in route_b
, the active class will be applied.
This works just having a logic function on the right that returns true or false.
So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.
By the way, I forgot to give you the function isActive():
$rootScope.isActive = function(viewLocation) {
return viewLocation === $location.path();
};
NEW UPDATE
Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div
, you can use the following code (very useful in ng-repeat
):
<i class="fa" ng-class="{ 'fa-github' : type === 0,
'fa-linkedin' : type === 1,
'fa-skype' : type === 2,
'fa-google' : type === 3 }"></i>
Icons from Font Awesome
using that code wil give you a responsive video player with full control
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" width="640" height="480" src="https://www.youtube-nocookie.com/embed/Lw_e0vF1IB4" frameborder="0" allowfullscreen></iframe>
</div>
You'll want to check HTML5 Differences from HTML4: W3C Working Group Note 9 December 2014 for the complete differences. There are many new elements and element attributes. Some elements were removed and others have different semantic value than before.
There are also APIs defined, such as the use of canvas, to help build the next generation of web apps and make sure implementations are standardized.
Create file loadtime.php
<?php
class loadTime{
private $time_start = 0;
private $time_end = 0;
private $time = 0;
public function __construct(){
$this->time_start= microtime(true);
}
public function __destruct(){
$this->time_end = microtime(true);
$this->time = $this->time_end - $this->time_start;
echo "Loaded in $this->time seconds\n";
}
}
Than in the beggining of your script, after <?php
write include 'loadtime.php'; $loadtime=new loadTime();
When page is loaded at the end there will be written "Loaded in x seconds"
You could also simply link both cells, and have an =Cell formula in each column like, =Sheet2!A2
in Sheet 1 A2 and =Sheet2!B2
in Sheet 1 B2, and drag it down, and then sort those two columns the way you want.
This would be better if your unique items change also, then all you would do is sort and be done.
This one more version - this will help in generic
Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer
Sub Create()
Dim strFilePath As String
Dim strFileName As String
'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value
strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value
Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName
End Sub
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
Dim Q As String
Dim sOutputFileNamewithPath As String
Q = Chr$(34)
Dim sXML As String
'sXML = sXML & "<rows>"
' ''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
Dim iCount As Integer
iRow = iDataStartRow
iCount = 1
While Cells(iRow, 1) > ""
'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
For iCOl = 1 To iColCount - 1
If (iStartCol = iCOl) Then
sXML = sXML & "<" & strSubTag & ">"
End If
If (iEndCol = iCOl) Then
sXML = sXML & "</" & strSubTag & ">"
End If
If (iStartCol2 = iCOl) Then
sXML = sXML & "<" & strSubTag2 & ">"
End If
If (iEndCol2 = iCOl) Then
sXML = sXML & "</" & strSubTag2 & ">"
End If
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
sXML = sXML & Trim$(Cells(iRow, iCOl))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
Next
'sXML = sXML & "</row>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
''Write the entire file to sText
Open sOutputFileNamewithPath For Output As #nDestFile
Print #nDestFile, sXML
iRow = iRow + 1
sXML = ""
iCount = iCount + 1
Wend
'sXML = sXML & "</rows>"
Close
End Sub
Following is how I draw a checkbox in a table!
| Checkbox Experiments | [ ] unchecked header | [x] checked header |
| ---------------------|:---------------------:|:-------------------:|
| checkbox | [ ] row | [x] row |
string.match(/^[0-9]+$/) != null;
Here i have designed the list by the following design image. My listitem filename is Propertylistitem.xml and cellborder.xml is used drawable shape for the cellborder output, are show in this image. necessary code i added here.
FileName:propertylistitem.xml
<TableLayout... >
<TableRow... >
<TextView ...
android:background="@drawable/cellborder"
android:text="Amount"/>
</TableRow>
<TableRow... >
<TextView...
android:background="@drawable/cellborder"
android:text="5000"/>
</TableRow>
</TableLayout>
filename:cellborder.xml Here i just want only border in my design, so i put comment the solid color tag.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<!-- <solid android:color="#dc6888"/> -->
<stroke android:width="0.1dp" android:color="#ffffff"
/>
<padding android:left="0dp" android:top="0dp"
android:right="0dp" android:bottom="0dp" />
</shape>
You Can use below Simple Code:
function checkDelBoxes(pForm, boxName, parent)
{
for (i = 0; i < pForm.elements.length; i++)
if (pForm.elements[i].name == boxName)
pForm.elements[i].checked = parent;
}
Example for Using:
<a href="javascript:;" onclick="javascript:checkDelBoxes($(this).closest('form').get(0), 'CheckBox[]', true);return false;"> Select All
</a>
<a href="javascript:;" onclick="javascript:checkDelBoxes($(this).closest('form').get(0), 'CheckBox[]', false);return false;"> Unselect All
</a>
I resolved this issue by setting an email address in Git:
git config --global user.email "[email protected]"
All you need to do is change the string within the java.text.SimpleDateFormat
constructor to:
"MM-dd-yyyy HH:mm:ss".
Just use the appropriate letters to build the above string to match your input date.
Answer below is what I created to link html contents from another shared drive to the html page I would send out to managers. Of course, the path is relative to your using, but in my case, I would just send them the html, and everything else that is updated from load runner dynamically would be updated for me. Saves tons of paper, and they can play with the numbers as they see fit instead of just a hard copy this way.
SRC="file://///shareddrive/shareddrive-folder/username/scripting/testReport\contents.html" NAME="contents_frame" title="Table of Contents"
It is a not-often-acknowledged fact that the block size of a block cipher is also an important security consideration (though nowhere near as important as the key size).
Blowfish (and most other block ciphers of the same era, like 3DES and IDEA) have a 64 bit block size, which is considered insufficient for the large file sizes which are common these days (the larger the file, and the smaller the block size, the higher the probability of a repeated block in the ciphertext - and such repeated blocks are extremely useful in cryptanalysis).
AES, on the other hand, has a 128 bit block size. This consideration alone is justification to use AES instead of Blowfish.
Jquery version
var currentdate = new Date();
$('#DatePickerInputID').val($.datepicker.formatDate('dd-M-y', currentdate));