1) Database: Change Database default collation as utf8mb4
.
2) Table: Change table collation as CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
.
Query:
ALTER TABLE Tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
3) Code:
INSERT INTO tablename (column1, column2, column3, column4, column5, column6, column7)
VALUES ('273', '3', 'Hdhdhdhhzhzhzzhjzj ??? ?', 49, 1, '2016-09-13 08:02:29', '2016-09-13 08:02:29')
4) Set utf8mb4
in database connection:
$database_connection = new mysqli($server, $user, $password, $database_name);
$database_connection->set_charset('utf8mb4');
FOR SQLALCHEMY AND PYTHON
The encoding used for Unicode has traditionally been 'utf8'. However, for MySQL versions 5.5.3 on forward, a new MySQL-specific encoding 'utf8mb4' has been introduced, and as of MySQL 8.0 a warning is emitted by the server if plain utf8 is specified within any server-side directives, replaced with utf8mb3. The rationale for this new encoding is due to the fact that MySQL’s legacy utf-8 encoding only supports codepoints up to three bytes instead of four. Therefore, when communicating with a MySQL database that includes codepoints more than three bytes in size, this new charset is preferred, if supported by both the database as well as the client DBAPI, as in:
e = create_engine(
"mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
All modern DBAPIs should support the utf8mb4 charset.
<span color="red">red</span>
#!/bin/bash
# convert ansi-colored terminal output to github markdown
# to colorize text on github, we use <span color="red">red</span> etc
# depends on: aha, xclip
# license: CC0-1.0
# note: some tools may need other arguments than `--color=always`
# sample use: colors-to-github.sh diff a.txt b.txt
cmd="$1"
shift
(
echo '<pre>'
$cmd --color=always "$@" 2>&1 | aha --no-header
echo '</pre>'
) \
| sed -E 's/<span style="[^"]*color:([^;"]+);"/<span color="\1"/g' \
| sed -E 's/ style="[^"]*"//g' \
| xclip -i -sel clipboard
trivial :)
Maybe you can use float:right;:
.one {_x000D_
padding-left: 1em;_x000D_
text-color: white;_x000D_
display:inline; _x000D_
}_x000D_
.two {_x000D_
background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<h3 class="one">Text</h3>_x000D_
<button class="btn btn-secondary pull-right">Button</button>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
I had the same issue, I did the following to fix the problem.
gen - automated code in project (from dependencies and references)
src - source code in project
There was no need to restart the Eclipse. It just started working.
Honestly I have never tried "Android Tools > Fix Project Properties", sometimes it might be doing the same thing. I do not know, I just did above after seen the error message, thinking something is wrong with the build paths.
Edit
Later on it was not sufficient, I was getting the error again. Then I "checked" all the dependencies listed in that view. Now it works again. So far so good. I will keep this updated if it fails again.
FYI: in my last attempt, I tried "Android Tools > Fix Project Properties", but it didn't work out for me.
It seems clear that $(TESTS)
is empty so your 1.4.0 makefile is effectively
all:
clean:
rm -f gtest.a gtest_main.a *.o
Indeed, all has nothing to do. and clean does exactly what it says rm -f gtest.a ...
This one works pretty well with git-2.18.2 and can be launched from outside git target repository:
basename -s .git $(git --git-dir=/<project-path>/.git remote get-url origin)
I ran into this error when testing my Angular 6 App with Karma/Jasmine. I had already imported FormsModule
in my top-level module. But when I added a new component that used [(ngModel)]
my tests began failing. In this case, I needed to import FormsModule
in my TestBed
TestingModule
.
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
FormsModule
],
declarations: [
RegisterComponent
]
})
.compileComponents();
}));
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.
Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.
You can configure Git to store your password for you. For Windows:
git config --global credential.helper wincred
If you really have to iterate a Pandas dataframe, you will probably want to avoid using iterrows(). There are different methods and the usual iterrows()
is far from being the best. itertuples() can be 100 times faster.
In short:
df.itertuples(name=None)
. In particular, when you have a fixed number columns and less than 255 columns. See point (3)df.itertuples()
except if your columns have special characters such as spaces or '-'. See point (2)itertuples()
even if your dataframe has strange columns by using the last example. See point (4)iterrows()
if you cannot the previous solutions. See point (1)Generate a random dataframe with a million rows and 4 columns:
df = pd.DataFrame(np.random.randint(0, 100, size=(1000000, 4)), columns=list('ABCD'))
print(df)
1) The usual iterrows()
is convenient, but damn slow:
start_time = time.clock()
result = 0
for _, row in df.iterrows():
result += max(row['B'], row['C'])
total_elapsed_time = round(time.clock() - start_time, 2)
print("1. Iterrows done in {} seconds, result = {}".format(total_elapsed_time, result))
2) The default itertuples()
is already much faster, but it doesn't work with column names such as My Col-Name is very Strange
(you should avoid this method if your columns are repeated or if a column name cannot be simply converted to a Python variable name).:
start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
result += max(row.B, row.C)
total_elapsed_time = round(time.clock() - start_time, 2)
print("2. Named Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))
3) The default itertuples()
using name=None is even faster but not really convenient as you have to define a variable per column.
start_time = time.clock()
result = 0
for(_, col1, col2, col3, col4) in df.itertuples(name=None):
result += max(col2, col3)
total_elapsed_time = round(time.clock() - start_time, 2)
print("3. Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))
4) Finally, the named itertuples()
is slower than the previous point, but you do not have to define a variable per column and it works with column names such as My Col-Name is very Strange
.
start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
result += max(row[df.columns.get_loc('B')], row[df.columns.get_loc('C')])
total_elapsed_time = round(time.clock() - start_time, 2)
print("4. Polyvalent Itertuples working even with special characters in the column name done in {} seconds, result = {}".format(total_elapsed_time, result))
Output:
A B C D
0 41 63 42 23
1 54 9 24 65
2 15 34 10 9
3 39 94 82 97
4 4 88 79 54
... .. .. .. ..
999995 48 27 4 25
999996 16 51 34 28
999997 1 39 61 14
999998 66 51 27 70
999999 51 53 47 99
[1000000 rows x 4 columns]
1. Iterrows done in 104.96 seconds, result = 66151519
2. Named Itertuples done in 1.26 seconds, result = 66151519
3. Itertuples done in 0.94 seconds, result = 66151519
4. Polyvalent Itertuples working even with special characters in the column name done in 2.94 seconds, result = 66151519
This article is a very interesting comparison between iterrows and itertuples
I know the topic is quite old, but such tools are always handy. I've used the resources above and created a version of NtpClient which allows asynchronously to acquire accurate time, instead of event based.
/// <summary>
/// Represents a client which can obtain accurate time via NTP protocol.
/// </summary>
public class NtpClient
{
private readonly TaskCompletionSource<DateTime> _resultCompletionSource;
/// <summary>
/// Creates a new instance of <see cref="NtpClient"/> class.
/// </summary>
public NtpClient()
{
_resultCompletionSource = new TaskCompletionSource<DateTime>();
}
/// <summary>
/// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
/// </summary>
/// <returns>Network accurate <see cref="DateTime"/> value.</returns>
public async Task<DateTime> GetNetworkTimeAsync()
{
return await GetNetworkTimeAsync(TimeSpan.FromSeconds(45));
}
/// <summary>
/// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
/// </summary>
/// <param name="timeoutMs">Operation timeout in milliseconds.</param>
/// <returns>Network accurate <see cref="DateTime"/> value.</returns>
public async Task<DateTime> GetNetworkTimeAsync(int timeoutMs)
{
return await GetNetworkTimeAsync(TimeSpan.FromMilliseconds(timeoutMs));
}
/// <summary>
/// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
/// </summary>
/// <param name="timeout">Operation timeout.</param>
/// <returns>Network accurate <see cref="DateTime"/> value.</returns>
public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
{
using (var socket = new DatagramSocket())
using (var ct = new CancellationTokenSource(timeout))
{
ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());
socket.MessageReceived += OnSocketMessageReceived;
//The UDP port number assigned to NTP is 123
await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
using (var writer = new DataWriter(socket.OutputStream))
{
// NTP message size is 16 bytes of the digest (RFC 2030)
var ntpBuffer = new byte[48];
// Setting the Leap Indicator,
// Version Number and Mode values
// LI = 0 (no warning)
// VN = 3 (IPv4 only)
// Mode = 3 (Client Mode)
ntpBuffer[0] = 0x1B;
writer.WriteBytes(ntpBuffer);
await writer.StoreAsync();
var result = await _resultCompletionSource.Task;
return result;
}
}
}
private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
try
{
using (var reader = args.GetDataReader())
{
byte[] response = new byte[48];
reader.ReadBytes(response);
_resultCompletionSource.TrySetResult(ParseNetworkTime(response));
}
}
catch (Exception ex)
{
_resultCompletionSource.TrySetException(ex);
}
}
private static DateTime ParseNetworkTime(byte[] rawData)
{
//Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
const byte serverReplyTime = 40;
//Get the seconds part
ulong intPart = BitConverter.ToUInt32(rawData, serverReplyTime);
//Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(rawData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
DateTime networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
// stackoverflow.com/a/3294698/162671
private static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
}
Usage:
var ntp = new NtpClient();
var accurateTime = await ntp.GetNetworkTimeAsync(TimeSpan.FromSeconds(10));
You can use just:
"{0:b}".format(n)
In my opinion this is the easiest way!
Can't you create a subclass of Dictionary which has that functionality?
public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >
{
private Dictionary < TValue, TKey > _keys;
public TValue this[TKey key]
{
get
{
return base[key];
}
set
{
base[key] = value;
_keys[value] = key;
}
}
public MyDict()
{
_keys = new Dictionary < TValue, TKey >();
}
public TKey GetKeyFromValue(TValue value)
{
return _keys[value];
}
}
EDIT: Sorry, didn't get code right first time.
I use named action
instead of javascript because javascript often is disabled, and if it isn't it gives a warning.
My web application creates a postscript file that then is converted with ghostscript to a pdf. I want it to print automatically because the user has already clicked on print inside my application. With the information about named actions from @DSimon above, I researched how to solve this. It all boils down to insert the string /Type /Action /S /Named /N /Print
at the right place in the pdf.
I was thinking of writing a small utility, but it has to parse the pdf to find the root node, insert /OpenAction
with a reference an object with the action, and recalculate the byte-offsets in xref.
But then I found out about pdfmark which is an extension to postscript to express, in postscript syntax, idioms that are converted to pdf by Adobes distiller or by ghostscript.
Since I'm already using ghostscript, all I have to do is append the following to the end of my postscript file:
%AUTOPRINT
[ /_objdef {PrintAction} /type /dict /OBJ pdfmark
[ {PrintAction} << /Type /Action /S /Named /N /Print >> /PUT pdfmark
[ {Catalog} << /OpenAction {PrintAction} >> /PUT pdfmark
and ghostscript will create the action, link it, and calculate the xref offsets. (In postscript %
is a comment and PrintAction
is my name for the object)
By looking at the PDF I see that it has created this:
1 0 obj
<</Type /Catalog /Pages 3 0 R
/OpenAction 9 0 R
/Metadata 10 0 R
>>
endobj
9 0 obj
<</S/Named
/Type/Action
/N/Print>>endobj
1 0
is object 1, revision 0, and 9 0
is object 9, revision 0. In the pdf-trailer is says that it is object 1 that is the root node. As you can see there is a reference from object 1, /OpenAction
to run object 9 revision 0.
With ghostscript it's possible to convert a pdf to postscript (pdf2ps), append the text above, and convert it back to pdf with ps2pdf
. It should be noted that meta-information about the pdf is lost in this conversion. I haven't searched more into this.
My workaround since none of the above appear to work in Chrome 63 and beyond
I fixed this on my site by replacing the offending input element with
<p class="input" contenteditable="true"> </p>
and using jQuery to populate a hidden field prior to submission.
But this is a truly awful hack made necessary by a bad decision at Chromium.
For OS X users (Mojave 10.14.3)
Here is what i use in my Bash script to test if Docker is running or not
# Check if docker is running
if ! docker info >/dev/null 2>&1; then
echo "Docker does not seem to be running, run it first and retry"
exit 1
fi
create java application in which you define two threads namely t1 and t2, thread t1 will generate random number 0 and 1 (simulate toss a coin ). 0 means head and one means tail. the other thread t2 will do the same t1 and t2 will repeat this loop 100 times and finally your application should determine how many times t1 guesses the number generated by t2 and then display the score. for example if thread t1 guesses 20 number out of 100 then the score of t1 is 20/100 =0.2 if t1 guesses 100 numbers then it gets score 1 and so on
I ran into this issue and my problem was a bit more involved... Originally I was trying to restore a SQL Server 2000 backup to SQL Server 2012. Of course this didn't work cause SQL server 2012 only supports backups from 2005 and upwards .
So, I restored the database on a SQL Server 2008 machine. Once this was done - I copied the database over to restore on SQL Server 2012 - and it failed with the following error
The media family on device 'C:\XXXXXXXXXXX.bak' is incorrectly formed. SQL Server cannot process this media family. RESTORE HEADERONLY is terminating abnormally. (Microsoft SQL Server, Error: 3241)
After a lot of research I found that I had skipped a step - I had to go back to the SQL Server 2008 machine and Right Click On the database(that I wanted to backup)> Properties > Options > Make sure compatibility level is set to SQL Server 2008. > Save
And then re-create the backup - After this I was able to restore to SQL Server 2012.
Use subscripting to access the value for a dictionary key. This will return an Optional:
let apple: String? = companies["AAPL"]
or
if let apple = companies["AAPL"] {
// ...
}
You can also enumerate over all of the keys and values:
var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
for (key, value) in companies {
print("\(key) -> \(value)")
}
Or enumerate over all of the values:
for value in Array(companies.values) {
print("\(value)")
}
Inside your project folder their is a bin folder. Inside your bin folder, there are 2 folders, a Release and a Debug. For your polished .exe, you want to go into your Release folder.
I'm not quite sure if thats what youre asking
I'm assuming you are using jQuery or something similar. If you are using jQuery, then the following should work:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
content
</body>
<script type="text/javascript">
$("body").load(url);
</script>
</html>
this is what you have to do.
decimal d = 1200.00;
string value = d.ToString(CultureInfo.InvariantCulture);
// value = "1200.00"
This worked for me. Thanks.
It seems to be a bug, it work for all input type that aren't textbox (checkboxes, radio,...)
There is a quick workaround that will work.
<div data-tip="This is the text of the tooltip2">
<input type="text" name="test" value="44"/>
</div>
You can also apply the default 'text' classes available from bootstrap itself
<h1 class='text-info'>Hey... I'm blue</h1>
Try it: tableView.reloadSections(IndexSet(integersIn: 0...0), with: .automatic) It helped me
Either you do what redsquare proposes with this code:
function preventDefault(e) {
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now switching back
$("form#foo").unbind("submit", preventDefault);
Or you assign a form attribute whenever submission is allowed. Something like this:
function preventDefault(e) {
if (event.currentTarget.allowDefault) {
return;
}
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now allowing submissions on the form
$("form#foo").get(0).allowDefault = true;
I would wrap your rows in labels
<form action="doit" id="doit" method="post">
<label>
Name
<input id="name" name="name" type="text" />
</label>
<label>
Phone number
<input id="phone" name="phone" type="text" />
</label>
<label>
Year
<input id="year" name="year" type="text" />
</label>
</form>
And use
label, input {
display: block;
}
label {
margin-bottom: 20px;
}
Don't use br
s for spacing!
In HTML file you can add ngIf for you pattern like this
<div class="form-control-feedback" *ngIf="Mobile.errors && (Mobile.dirty || Mobile.touched)">
<p *ngIf="Mobile.errors.pattern" class="text-danger">Number Only</p>
</div>
In .ts file you can add the Validators pattern - "^[0-9]*$"
this.Mobile = new FormControl('', [
Validators.required,
Validators.pattern("^[0-9]*$"),
Validators.minLength(8),
]);
Use git checkout -
You will see Switched to branch <branch_name>
. Confirm it's the branch you want.
Brief explanation: this command will move HEAD back to its last position. See note on outcomes at the end of this answer.
Mnemonic: this approach is a lot like using cd -
to return to your previously visited directory. Syntax and the applicable cases are a pretty good match (e.g. it's useful when you actually want HEAD to return to where it was).
The quick approach solves the OP's question. But what if your situation is slightly different: say you have restarted Bash then found yourself with HEAD detached. In that case, here are 2 simple, easily remembered steps.
Use git branch -v
You see a list of existing local branches. Grab the branch name that suits your needs.
Use git checkout <branch_name>
You will see Switched to branch <branch_name>
. Success!
With either method, you can now continue adding and committing your work as before: your next changes will be tracked on <branch_name>
.
Note that both git checkout -
and git checkout <branch_name>
will give additional instructions if you have committed changes while HEAD was detached.
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
The below code will help you to auto open the .exe file from excel...
Sub Auto_Open()
Dim x As Variant
Dim Path As String
' Set the Path variable equal to the path of your program's installation
Path = "C:\Program Files\GameTop.com\Alien Shooter\game.exe"
x = Shell(Path, vbNormalFocus)
End Sub
About the recalculation:
You can keep your set of random values from changing every time you make an adjustment, by adjusting the automatic recalculation
, to: manual recalculate
. (Re)calculations are then only done when you press F9. Or shift F9.
See this link (though for older excel version than the current 2013) for some info about it: https://support.office.com/en-us/article/Change-formula-recalculation-iteration-or-precision-73fc7dac-91cf-4d36-86e8-67124f6bcce4.
Use ack. Checkout its --passthru
option here: ack. It has the added benefit of allowing full perl regular expressions.
$ ack --passthru 'pattern1' file_name
$ command_here | ack --passthru 'pattern1'
You can also do it using grep like this:
$ grep --color -E '^|pattern1|pattern2' file_name
$ command_here | grep --color -E '^|pattern1|pattern2'
This will match all lines and highlight the patterns. The ^
matches every start of line, but won't get printed/highlighted since it's not a character.
(Note that most of the setups will use --color by default. You may not need that flag).
You can also see this error when selecting for a union where corresponding columns can be null.
select * from (select D.dept_no, D.nullable_comment
from dept D
union
select R.dept_no, NULL
from redundant_dept R
)
This apparently confuses the parser, a solution is to assign a column alias to the always null column.
select * from (select D.dept_no, D.comment
from dept D
union
select R.dept_no, NULL "nullable_comment"
from redundant_dept R
)
The alias does not have to be the same as the corresponding column, but the column heading in the result is driven by the first query from among the union members, so it's probably a good practice.
Try the zsh. It supports suffix alias, so you can define X in your .zshrc to be
alias -g X="| cut -d' ' -f2"
then you can do:
cat file X
You can take it one step further and define it for the nth column:
alias -g X2="| cut -d' ' -f2"
alias -g X1="| cut -d' ' -f1"
alias -g X3="| cut -d' ' -f3"
which will output the nth column of file "file". You can do this for grep output or less output, too. This is very handy and a killer feature of the zsh.
You can go one step further and define D to be:
alias -g D="|xargs rm"
Now you can type:
cat file X1 D
to delete all files mentioned in the first column of file "file".
If you know the bash, the zsh is not much of a change except for some new features.
HTH Chris
Just use android:focusableInTouchMode="false"
on your webView.
A other users suggested,
.empty()
is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.
If you wish to keep data, like event handlers for example, you should use
.detach()
as described on the JQuery's API detach documentation.
The method .remove() could be usefull for similar purposes.
You don't need to escape the '
character in a String (wrapped in "
), and you don't have to escape a "
character in a char (wrapped in '
).
One possible way is using a deploy token (https://docs.gitlab.com/ee/user/project/deploy_tokens). After creating the token, use:
git clone https://<username>:<deploy_token>@gitlab.example.com/tanuki/awesome_project.git
as mentioned in the link above.
Today this also happened to me. The function name maybe conflicts with keywords. My case is scrape()
. I change the function name, everything works fine.
for i in range (1, len(list))
try:
print (list[i])
except ValueError:
print("Error Value.")
except indexError:
print("Erorr index")
except :
print('error ')
This looks cool.
-moz-box-shadow: 0 0 5px #999;
-webkit-box-shadow: 0 0 5px #999;
box-shadow: 0 0 5px #999;
The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *
. Also, the map
method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply
is used for.
So, if you must use the above approach, I would write it like this
df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
There's actually no reason to use zip here. You can simply do this:
df["A1"], df["A2"] = calculate(df['a'])
This second method is also much faster on larger DataFrames
df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})
DataFrame created with 300,000 rows
%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
60x faster than zip
Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above
%%timeit
A1, A2 = [], []
for val in df['a']:
A1.append(val**2)
A2.append(val**3)
df['A1'] = A1
df['A2'] = A2
298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:
%load_ext cython
%%cython
cpdef power(vals):
A1, A2 = [], []
cdef double val
for val in vals:
A1.append(val**2)
A2.append(val**3)
return A1, A2
%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
You can get even greater speed improvements if you use the direct vectorized operations.
%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.
apply
The above example should clearly show how slow apply
can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply
s = pd.Series(np.random.rand(10000000))
%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Without apply is 50x faster
%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Try running task manager to determine if your program is still running.
If it is running then stop it and run it again. the [Error] ld returned 1 exit status will not come back
The way I do is go to http://getbootstrap.com/customize/ and only check "grid system" to download. There are bootstrap-theme.css
and bootstrap.css
in downloaded files, and I only need the latter.
In this way, I can use the grid system of Bootstrap, with everything else from Material UI.
Check this SharpDOM . This is a c# 4.0 internal dsl for generating html and also asp.net mvc view engine.
If you use IEnumerable
instead, it will work (at least in C# 4.0, I have not tried previous versions). This is just a cast, of course, it will still be a list.
Instead of -
List<A> listOfA = new List<C>(); // compiler Error
In the original code of the question, use -
IEnumerable<A> listOfA = new List<C>(); // compiler error - no more! :)
Thank goodness I found this. The following is extremely important:
<meta http-equiv="X-UA-Compatible" content="IE=9" >
Without this, none of the reports I'd been generating would work post IE9 install despite having worked great in IE8. They would show up properly in a web browser control, but there would be missing letters, jacked up white space, etc, when I called .Print(). They were just basic HTML that should be capable of being rendered even in Mosaic. heh Not sure why the IE7 compatibility mode was going haywire. Notably, you could .Print() the same page 5 times and have it be missing different letters each time. It would even carry over into PDF output, so it's definitely the browser.
There are a number of approaches here- and though the position is that typically users should not be restricted when it comes to zooming for accessibility purposes, there may be incidences where is it required:
Render the page at the width of the device, dont scale:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Prevent scaling- and prevent the user from being able to zoom:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
Removing all zooming, all scaling
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
For the Android library projects, I do it as in the attached screenshot:
Right click the project, select Properties->Android and in the library section click Add. From here you can select the available libraries.
If you are importing a jar file, then importing them as jar or external jar, as other posters posted would work. I prefer to copy/paste jar file in the libs folder (create one if it doesn't exist) and then import as jar.
If you mean by newline the newline character it is \n and \r is the carrier return character, but if you mean by newline the line ending then it depends on the operating system: DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n")
In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml
), you can do so by just putting an array of mappings in the @WebFilter
annotation:
/**
* Filter implementation class LoginFilter
*/
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
...
And just as an FYI, this same thing works for servlets using the servlet annotation too:
/**
* Servlet implementation class LoginServlet
*/
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
...
Well, you can't quite do it that way. PAGE.SIGN_CREATE
will never return 1; it will return PAGE.SIGN_CREATE
. That's the point of enumerated types.
However, if you're willing to add a few keystrokes, you can add fields to your enums, like this:
public enum PAGE{
SIGN_CREATE(0),
SIGN_CREATE_BONUS(1),
HOME_SCREEN(2),
REGISTER_SCREEN(3);
private final int value;
PAGE(final int newValue) {
value = newValue;
}
public int getValue() { return value; }
}
And then you call PAGE.SIGN_CREATE.getValue()
to get 0.
The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.
No it won't, Java will short-circuit and stop evaluating once it knows the result.
Something along the lines of this?
<asp:TextBox id="txtUsername" runat="server" />
<asp:RegularExpressionValidator
id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Field not valid!"
ControlToValidate="txtUsername"
ValidationExpression="[0-9a-zA-Z]{6,}" />
The first one catches all subclasses of Throwable
(this includes Exception
and Error
), the second one catches all subclasses of Exception
.
Error
is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception
is programmatically recoverable. Its subclass RuntimeException
indicates a programming error and is usually not to be caught as well.
There are many ways to hide all elements which has certain class in javascript one way is to using for loop but here i want to show you other ways to doing it.
1.forEach and querySelectorAll('.classname')
document.querySelectorAll('.classname').forEach(function(el) {
el.style.display = 'none';
});
2.for...of with getElementsByClassName
for (let element of document.getElementsByClassName("classname")){
element.style.display="none";
}
3.Array.protoype.forEach getElementsByClassName
Array.prototype.forEach.call(document.getElementsByClassName("classname"), function(el) {
// Do something amazing below
el.style.display = 'none';
});
4.[ ].forEach and getElementsByClassName
[].forEach.call(document.getElementsByClassName("classname"), function (el) {
el.style.display = 'none';
});
i have shown some of the possible ways, there are also more ways to do it, but from above list you can Pick whichever suits and easy for you.
Note: all above methods are supported in modern browsers but may be some of them will not work in old age browsers like internet explorer.
Since expression is boolean:
return expression;
You can use exec
for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
If you need to use in Fragment you should use
private Context context;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
((MainActivity)context).runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
instead of
getActivity().runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
Because There will be null pointer exception in some situation like pager fragment
If you are connecting from Windows machine A to Windows machine B (server with SQL Server installed), and are getting this error, you need to do the following:
On machine B:
1.) turn on the Windows service called "SQL Server Browser" and start the service
2.) in the Windows firewall, enable incoming port UDP 1434 (in case SQL Server Management Studio on machine A is connecting or a program on machine A is connecting)
3.) in the Windows firewall, enable incoming port TCP 1433 (in case there is a telnet connection)
4.) in SQL Server Configuration Manager, enable TCP/IP protocol for port 1433
I found that applying the -webkit-backface-visibility: hidden;
to the translating element and -webkit-transform: translate3d(0,0,0);
to all its children, the flicker then disappears
You are importing the module datetime, which doesn't have a strptime
function.
That module does have a datetime
object with that method though:
import datetime
dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")
Alternatively you can import the datetime
object from the module:
from datetime import datetime
dtDate = datetime.strptime(sDate, "%m/%d/%Y")
Note that the strptime
method was added in python 2.5; if you are using an older version use the following code instead:
import datetime, time
dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])
The reason why you get your error is because a "1 by n" matrix is different from an array of length n.
I recommend using hstack()
and vstack()
instead.
Like this:
import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:] # last column of that matrix.
result = np.hstack((a,b)) # stack them horizontally like this:
#array([[ 0, 1, 2, 3, 4, 5, 6, 7, 7],
# [ 8, 9, 10, 11, 12, 13, 14, 15, 15],
# [16, 17, 18, 19, 20, 21, 22, 23, 23],
# [24, 25, 26, 27, 28, 29, 30, 31, 31]])
Notice the repeated "7, 15, 23, 31" column.
Also, notice that I used a[:,-1:]
instead of a[:,-1]
. My version generates a column:
array([[7],
[15],
[23],
[31]])
Instead of a row array([7,15,23,31])
Edit: append()
is much slower. Read this answer.
I also used the bash4 way but I find and annoying bug.
I needed to update dynamically the associative array content so i used this way:
for instanceId in $instanceList
do
aws cloudwatch describe-alarms --output json --alarm-name-prefix $instanceId| jq '.["MetricAlarms"][].StateValue'| xargs | grep -E 'ALARM|INSUFFICIENT_DATA'
[ $? -eq 0 ] && statusCheck+=([$instanceId]="checkKO") || statusCheck+=([$instanceId]="allCheckOk"
done
I find out that with bash 4.3.11 appending to an existing key in the dict resulted in appending the value if already present. So for example after some repetion the content of the value was "checkKOcheckKOallCheckOK" and this was not good.
No problem with bash 4.3.39 where appenging an existent key means to substisture the actuale value if already present.
I solved this just cleaning/declaring the statusCheck associative array before the cicle:
unset statusCheck; declare -A statusCheck
It's possible.
From an arcticle on TrueAffection.net.
- Download PCKeyboardHack and install it.
- Go to PCKeyboardHack in System Preferences.
- Enable ‘Change Caps Lock’ and set the keycode to 53.
This solution doesn't involve patching the keyboard driver, but gives you a Vim specific solution.
OS X supports mapping the Caps Lock key to a whole bunch of keys, but you have to do it 'by hand', editting .plist files. The process is described in this article. As addendum to that hint I suggest you first set Caps-Lock to None in the System Preferences, then you only need to change one value in the .plist file. Also, you can of course use the Property List Editor instead of going through the XML conversion steps.
The trick is to map the Caps Lock key to the Help key (code 6), which isn't on most keyboards. But if it is, it will be treated as the insert key, which you probably don't use anyway, since you ask about remapping your Caps Lock to prevent stretching your hands ;)
You can then map the Help and the Insert key to Esc in vim.
map <Help> <Esc>
map! <Help> <Esc>
map <Insert> <Esc>
map! <Insert> <Esc>
This will work for gvim (Vim.app). I didn't get it to work with vim in the Terminal and I haven't tested it with MacVim.
So, it's rather a complicated, half-baked solution or installing a third-party piece of hackery. Your pick ;)
Edit: Just noticed solution 3, if you're using MacVim you can use Ctrl, Option and Command as Esc. With the System Preferences it's trivial to map Caps Lock to one of those keys.
$session_start();
extract($_POST);
//extract data from submit post
if(isset($submit))
{
if($user=="user" && $pass=="pass")
{
$_SESSION['user']= $user;
//if correct password and name store in session
}
else {
echo "Invalid user and password";
header("Locatin:form.php");
}
if(isset($_SESSION['user']))
{
//your home page code here
exit;
}
I had a similar issue in MVC (which lead me to this problem).
I am receiving a FORM as a string response from a WebClient.UploadValues() request, which I then have to submit - so I can't use a second WebClient or HttpWebRequest. This request returned the string.
using (WebClient client = new WebClient())
{
byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection()
{
{ "test", "value123" }
});
result = System.Text.Encoding.UTF8.GetString(response);
}
My solution, which could be used to solve the OP, is to append a Javascript auto submit to the end of the code, and then using @Html.Raw() to render it on a Razor page.
result += "<script>self.document.forms[0].submit()</script>";
someModel.rawHTML = result;
return View(someModel);
Razor Code:
@model SomeModel
@{
Layout = null;
}
@Html.Raw(@Model.rawHTML)
I hope this can help anyone who finds themselves in the same situation.
This solutions sounds crazy, but works smooth as honey
import csv
with open('filename', 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL,delimiter='\n')
wr.writerow(mylist)
The file is being written by csvwriter hence csv properties are maintained i.e. comma separated. The delimiter helps in the main part by moving list items to next line, each time.
myArray.sample
will return 1 random value.
myArray.shuffle.first
will also return 1 random value.
Try:
using System.Diagnostics;
ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
string processpathfilename;
string processmodulename;
if (modules.Count > 0) {
processpathfilename = modules[0].FileName;
processmodulename= modules[0].ModuleName;
} else {
throw new ExecutionEngineException("Something critical occurred with the running process.");
}
Are you trying to submit a form?
Listen to the submit
event instead.
This will handle click
and enter
.
If you must use enter key...
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
You can use Configuration to resolve this.
Ex (Startup.cs):
You can pass by DI to the controllers after this implementation.
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var microserviceName = Configuration["microserviceName"];
services.AddSingleton(Configuration);
...
}
You can accomplish this using the mysqldump command-line function.
For example:
If it's an entire DB, then:
$ mysqldump -u [uname] -p db_name > db_backup.sql
If it's all DBs, then:
$ mysqldump -u [uname] -p --all-databases > all_db_backup.sql
If it's specific tables within a DB, then:
$ mysqldump -u [uname] -p db_name table1 table2 > table_backup.sql
You can even go as far as auto-compressing the output using gzip (if your DB is very big):
$ mysqldump -u [uname] -p db_name | gzip > db_backup.sql.gz
If you want to do this remotely and you have the access to the server in question, then the following would work (presuming the MySQL server is on port 3306):
$ mysqldump -P 3306 -h [ip_address] -u [uname] -p db_name > db_backup.sql
It should drop the .sql
file in the folder you run the command-line from.
EDIT: Updated to avoid inclusion of passwords in CLI commands, use the -p
option without the password. It will prompt you for it and not record it.
If your dates
column does not contain time information, you could get away with:
WHERE dates BETWEEN '20121211' and '20121213'
However, given your dates
column is actually datetime, you want this
WHERE dates >= '20121211'
AND dates < '20121214' -- i.e. 00:00 of the next day
Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:
WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'
Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.
I faced this issue, when I was supplying the executable folder with a, by the .exe requested DLL. In my case, the DLL I supplied to the .exe was searching for another necessary DLL which was not available. The searching DLL was not capable of telling that it can not find the necessary DLL.
You might check the DLLs you're loading and the dependencies of these DLL's.
For security reasons most browsers do not allow to modify the clipboard (except IE, of course...).
The only way to make a copy-to-clipboard function cross-browser compatible is to use Flash.
I've run into this error dozens of times:
Cause
Security permissions were not properly set when the Oracle client was installed on Windows with NTFS. The result of this is that content of the ORACLE_HOME
directory is not visible to Authenticated Users on the machine; this causes an error while the System.Data.OracleClient
is communicating with the Oracle Connectivity software from ASP.NET using Authenticated User privileges.
Solution
To fix the problem you have to give the Authenticated Users group privilege to the Oracle Home directory.
ORACLE_HOME
folder.ORACLE_HOME
folder.Try your application again.
Swift 3
private let NUMBER_COUNT_DOWN = 3
var countDownLabel = UILabel()
var countDown = NUMBER_COUNT_DOWN
var timer:Timer?
private func countDown(time: Double)
{
countDownLabel.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
countDownLabel.font = UIFont.systemFont(ofSize: 300)
countDownLabel.textColor = .black
countDownLabel.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
countDownLabel.textAlignment = .center
self.view.addSubview(countDownLabel)
view.bringSubview(toFront: countDownLabel)
timer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(updateCountDown), userInfo: nil, repeats: true)
}
func updateCountDown() {
if(countDown > 0) {
countDownLabel.text = String(countDown)
countDown = countDown - 1
} else {
removeCountDownLable()
}
}
private func removeCountDownLable() {
countDown = NUMBER_COUNT_DOWN
countDownLabel.text = ""
countDownLabel.removeFromSuperview()
timer?.invalidate()
timer = nil
}
In plt.colorbar(z1_plot,cax=ax1)
, use ax=
instead of cax=
, i.e. plt.colorbar(z1_plot,ax=ax1)
== is what you want, "is" just happens to work on your examples.
Note to Sinan and brian: perlfaq3 is still wrong.
If you are in a network of users, then the username will be different:
Environment.UserName
Will Display format : 'Username', rather than
System.Security.Principal.WindowsIdentity.GetCurrent().Name
Will Display format : 'NetworkName\Username'
Choose the format you want.
For a Windows Store App, you won't have HttpUtility. Instead, you have:
For an URI, before the '?':
For an URI query name or value, after the '?':
For a x-www-form-urlencoded query name or value, in a POST content:
Write a class A, that contains of an array of class B. Class B should have an id property and a value property. Deserialize the xml to class A. Convert the array in A to the wanted dictionary.
To serialize the dictionary convert it to an instance of class A, and serialize...
If you want to just "set" the actual filename, without incurring the overhead of loading and re-saving the file (!!), or resorting to using a charfield (!!!), you might want to try something like this --
model_instance.myfile = model_instance.myfile.field.attr_class(model_instance, model_instance.myfile.field, 'my-filename.jpg')
This will light up your model_instance.myfile.url and all the rest of them just as if you'd actually uploaded the file.
Like @t-stone says, what we really want, is to be able to set instance.myfile.path = 'my-filename.jpg', but Django doesn't currently support that.
The problem here is very simple. If you want to display value in JSP, you have to use <%= %> tag instead of <% %>, here is the solved code:
<tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getString("SKILL") %></td>
</tr>
You can paste the .jar file of the driver in the Java setup instead of adding it to each project that you create. Paste it in C:\Program Files\Java\jre7\lib\ext or wherever you have installed java.
After this you will find that the .jar driver is enlisted in the library folder of your created project(JRE system library) in the IDE. No need to add it repetitively.
To exclude certain characters ( <, >, %, and $), you can make a regular expression like this:
[<>%\$]
This regular expression will match all inputs that have a blacklisted character in them. The brackets define a character class, and the \ is necessary before the dollar sign because dollar sign has a special meaning in regular expressions.
To add more characters to the black list, just insert them between the brackets; order does not matter.
According to some Java documentation for regular expressions, you could use the expression like this:
Pattern p = Pattern.compile("[<>%\$]");
Matcher m = p.matcher(unsafeInputString);
if (m.matches())
{
// Invalid input: reject it, or remove/change the offending characters.
}
else
{
// Valid input.
}
If anyone can looking to display date with time in AM or PM in angular 6 then this is for you.
{{date | date: 'dd/MM/yyyy hh:mm a'}}
Output
Pre-defined format options
Examples are given in en-US locale.
'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
'shortDate': equivalent to 'M/d/yy' (6/15/15).
'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
'shortTime': equivalent to 'h:mm a' (9:03 AM).
'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).
#include <iostream>
int main()
{
int v[100] = {5,14,2,4,6};
int n = 5;
int mic = v[0];
for(int i = 0; i != n; ++i)
{
if(v[i] < mic)
mic = v[i];
}
std:cout << mic << std::endl;;
}
Well it depends on what you have in your table.
its one of the following If you have only one table
var count = $('#gvPerformanceResult tr').length;
If you are concerned about sub tables but this wont work with tbody and thead (if you use them)
var count = $('#gvPerformanceResult>tr').length;
Where by this will work (but is quite frankly overkill.)
var count = $('#gvPerformanceResult>tbody>tr').length;
Call Wget for each link and set it to run in background.
I tried this Python code
with open('links.txt', 'r')as f1: # Opens links.txt file with read mode
list_1 = f1.read().splitlines() # Get every line in links.txt
for i in list_1: # Iteration over each link
!wget "$i" -bq # Call wget with background mode
Parameters :
b - Run in Background
q - Quiet mode (No Output)
I found this answer while looking for a way to do that with a Dictionary, and it turns out it's quite easy to adapt it, just pass a tuple for the element.
// Swift 2
var list = ["a": 1, "b": 2]
for (index, (letter, value)) in list.enumerate() {
print("Item \(index): \(letter) \(value)")
}
Also be careful with double-quotes -- on the Unix shell this expands variables. Some are obvious (like $foo
and \t
) but some are not (like !foo
).
For safety, use single-quotes!
Simply: It's a warning by which the compiler indicates that it cannot ensure type safety.
JPA service method for example:
@SuppressWarnings("unchecked")
public List<User> findAllUsers(){
Query query = entitymanager.createQuery("SELECT u FROM User u");
return (List<User>)query.getResultList();
}
If I didn'n anotate the @SuppressWarnings("unchecked") here, it would have a problem with line, where I want to return my ResultList.
In shortcut type-safety means: A program is considered type-safe if it compiles without errors and warnings and does not raise any unexpected ClassCastException s at runtime.
I build on http://www.angelikalanger.com/GenericsFAQ/FAQSections/Fundamentals.html
Simplest answer:
(1) Download the curl binary here: https://curl.haxx.se/download.html (see the binary for your OS). Example:
(2) Create a folder "C:\curl" then unzip all there
(3) Edit the system variable called "Path" by adding ";C:\curl\bin" in the end. Finished.
Obs.: I've seen some guys telling to add ";C:\curl" but this way it's not possible to access curl.exe.
You can do this with jQuery. Using their selectors, you can select by attributes, such as type. This does, however, require that your users have Javascript turned on, and an additional file to download, but if it works...
You have to find the right user that needs to use temp folder. In my computer I follow the above link and find the special folder c:\inetpub, that iis use to execute her web services. I check what users could use these folder and find something like these: computername\iis_isusrs
The main issue comes when you try to add it to all permit on temp folder I was going to properties, security tab, edit button, add user button then i put iis_isusrs
and "check names" button
It doesn´t find anything The reason is the in my case it looks ( windows 2008 r2 iis 7 ) on pdgs.local location You have to go to "Select Users or Groups" form, click on Advanced button, click on Locations button and will see a specific hierarchy
So when you try to add an user, its search name on pdgs.local. You have to select computername and click ok, Click on "Find Now"
Look for IIS_IUSRS on Name(RDN) column, click ok. So we go back to "Select Users or Groups" form with new and right user underline
click ok, allow full control, and click ok again.
That´s all folks, Hope it helps,
Jose from Moralzarzal ( Madrid )
This will work even if you have two or more rows for each home
with equal DATETIME
's:
SELECT id, home, datetime, player, resource
FROM (
SELECT (
SELECT id
FROM topten ti
WHERE ti.home = t1.home
ORDER BY
ti.datetime DESC
LIMIT 1
) lid
FROM (
SELECT DISTINCT home
FROM topten
) t1
) ro, topten t2
WHERE t2.id = ro.lid
Here is a helper that I wrote to solve this issue for my projects. It makes it super simple and easy to be able to clear everything out quickly and with a single command.
Just use this this decrypter to decrypt your locally cached username & password.
By default, TortoiseSVN stores your cached credentials inside files in the %APPDATA%\Subversion\auth\svn.simple directory. The passwords are encrypted using the Windows Data Protection API, with a key tied to your user account. This tool reads the files and uses the API to decrypt your passwords
If you are using pgAdmin4 in PostgreSQL, you can use this to show the tables in your database:
select * from information_schema.tables where table_schema='public';
I had a similar situation. Here's what I was able to do to get a date range in a "where" clause (a modification of marc_s's answer):
where cast(replace(foo.TestDate, '-', '') as datetime)
between cast('20110901' as datetime) and
cast('20510531' as datetime)
Hope that helps...
By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.
You need to explicitly ask for the content type.
Add this line:
request.ContentType = "application/json; charset=utf-8";
At the appropriate place
I do not think that is possible you have to set all the values individualling (like the first example you provided.)
The Second example you gave, will only Initialize the last varuable to "" and not the others.
This is the way:
/usr/bin/php -q /home/username/public_html/yourfilename.php >/dev/null
If possible, let us locate/identify the busy process, kill that process and then unmount
the samba share/ drive to minimize damage:
lsof | grep '<mountpoint of /dev/sda1>'
(or whatever the mounted device is)
pkill target_process
(kills busy proc. by name | kill PID
| killall target_process
)
umount /dev/sda1
(or whatever the mounted device is)
There is a finishAffinity()
method in Activity
that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher.
For API 16+, use
finishAffinity();
For lower (Android 4.1 lower), use
ActivityCompat.finishAffinity(YourActivity.this);
assuming chrome is his default browser: start http://url.site.you.com/path/to/joke
should open that url in his browser.
import datetime
monthinteger = 4
month = datetime.date(1900, monthinteger, 1).strftime('%B')
print month
April
The error message clearly says that the default constructor has been deleted implicitly. It even says why: the class contains a non-static, const variable, which would not be initialized by the default ctor.
class X {
const int x;
};
Since X::x
is const
, it must be initialized -- but a default ctor wouldn't normally initialize it (because it's a POD type). Therefore, to get a default ctor, you need to define one yourself (and it must initialize x
). You can get the same kind of situation with a member that's a reference:
class X {
whatever &x;
};
It's probably worth noting that both of these will also disable implicit creation of an assignment operator as well, for essentially the same reason. The implicit assignment operator normally does members-wise assignment, but with a const member or reference member, it can't do that because the member can't be assigned. To make assignment work, you need to write your own assignment operator.
This is why a const
member should typically be static -- when you do an assignment, you can't assign the const member anyway. In a typical case all your instances are going to have the same value so they might as well share access to a single variable instead of having lots of copies of a variable that will all have the same value.
It is possible, of course, to create instances with different values though -- you (for example) pass a value when you create the object, so two different objects can have two different values. If, however, you try to do something like swapping them, the const member will retain its original value instead of being swapped.
Another approach is:
error(message: string, options?: {title?: string, autoHideAfter?: number});
So when you want to omit the title parameter, just send the data like that:
error('the message', { autoHideAfter: 1 })
I'd rather this options because allows me to add more parameter without having to send the others.
I have also faced the same issue while installing the XAMPP. The reason being the port 80 as configured in httpd.conf is already in use in other application (eg., in Skype). You can change the port value in httpd.conf to 8080 or other number. Click on config icon and open http.conf file. Search for 80 and do the following steps
In httpd.conf change
Listen 80 to Listen 8080
and
ServerName localhost:80 to
ServerName localhost:8080
You can check the ports used currently by clicking on netstatt icon in the XAMPP Control Panel
I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:
login : Debian Live User
password : live
I hope this helps
It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en
Without redundant intermediate arrays:
arr = $('li').map(function(i,el) {
return $(el).text();
}).get();
See jsfiddle demo
In 2021 the easiest way is to use asyncio:
import asyncio, time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(
say_after(4, 'hello'))
task2 = asyncio.create_task(
say_after(3, 'world'))
print(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
References:
If you're looking for a pure css option, try using the :focus pseudo class.
#style {
background-color: red;
}
#style:focus {
background-color:yellow;
}
guys This error because of Element Id not Visible from js Try to inspect element from UI and paste it on javascript file:
before :
document.getElementById('form:salesoverviewform:ticketstatusid').value =topping;
After :
document.getElementById('form:salesoverviewform:j_idt190:ticketstatusid').value =topping;
Credits to Divya Akka .... :)
The problem is your query returned false
meaning there was an error in your query. After your query you could do the following:
if (!$result) {
die(mysqli_error($link));
}
Or you could combine it with your query:
$results = mysqli_query($link, $query) or die(mysqli_error($link));
That will print out your error.
Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:
$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";
In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist
Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.
To add to Lennart Regebro's answer There is even the third way that can be used:
encoded3 = str.encode(original, 'utf-8')
print(encoded3)
Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.
A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.
Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.
In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".
The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.
If you really don't want to change your structure, or at least create a copy of it containing the same data (e.g. make a class property with a setter and getter that read from/write to that string behind the scenes), then you can use a regular expression to check if an item is in that "list" at any given time, and if not, append it to the "list" as a separate element.
if not re.match("\b{}\b".format(348521), some_list[0]): some_list.append(348521)
This is probably faster than converting it to a set every time you want to check if an item is in it. But using set
as others have suggested here is a million times better.
I ran into something similar - I wanted to create a range based on some variables. Using the Worksheet.Cells did not work directly since I think the cell's values were passed to Range.
This did work though:
Range(Cells(1, 1).Address(), Cells(lastRow, lastColumn).Address()).Select
That took care of converting the cell's numerical location to what Range expects, which is the A1 format.
RedirectMatch
uses a regular expression that is matched against the URL path. And your regular expression /contact.php
just means any URL path that contains /contact.php
but not just any URL path that is exactly /contact.php
. So use the anchors for the start and end of the string (^
and $)
:
RedirectMatch 301 ^/contact\.php$ /contact-us.php
NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:@":"];
_returnedArguments
is an array of NSStrings
which the UITextField text
property is expecting. No need to convert.
Syntax error:
[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];
If your _appDelegate has a passwordField
property, then you can set the text using the following
[[_appDelegate passwordField] setText:[_returnedArguments objectAtIndex:2]];
Use while loop like this:
while IFS= read -r line || [ -n "$line" ]; do
echo "$line"
done <file
Or using grep
with while loop:
while IFS= read -r line; do
echo "$line"
done < <(grep "" file)
Using grep .
instead of grep ""
will skip the empty lines.
Note:
Using IFS=
keeps any line indentation intact.
File without a newline at the end isn't a standard unix text file.
As the others have said, there is no difference in the compiled code (IL) when you use either of the following:
var x1 = new object();
object x2 = new object;
I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?
Consider the following and you'll get what I mean:
KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));
It's way easier to read this instead:
var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));
On Ubuntu 12.04, for example numpy package for python2, can be found at:
/usr/lib/python2.7/dist-packages/numpy
Of course, this is not generic answer
By default, git will update execute file permissions if you change them. It will not change or track any other permissions.
If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.
Look into your project, in the .git
folder for the config
file and you should see something like this:
[core]
filemode = false
You can either change it to true
in your favorite text editor, or run:
git config core.filemode true
Then, you should be able to commit normally your files. It will only commit the permission changes.
When you #include
a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal
variable is defined in the source so it will work no matter how it's declared.
Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.
The JavaScript Object()
constructor makes an Object that you can assign members to.
myObj = new Object()
myObj.key = value;
myObj[key2] = value2; // Alternative
DECLARE @StartDate datetime,@EndDate datetime
select @StartDate='3/2/2010', @EndDate='3/7/2010'
DECLARE @TotalDays INT,@WorkDays INT
DECLARE @ReducedDayswithEndDate INT
DECLARE @WeekPart INT
DECLARE @DatePart INT
SET @TotalDays= DATEDIFF(day, @StartDate, @EndDate) +1
SELECT @ReducedDayswithEndDate = CASE DATENAME(weekday, @EndDate)
WHEN 'Saturday' THEN 1
WHEN 'Sunday' THEN 2
ELSE 0 END
SET @TotalDays=@TotalDays-@ReducedDayswithEndDate
SET @WeekPart=@TotalDays/7;
SET @DatePart=@TotalDays%7;
SET @WorkDays=(@WeekPart*5)+@DatePart
SELECT @WorkDays
I don’t think that’s a good idea. Even if you find an appropriate regular expression (maybe using Unicode character properties), this wouldn’t prevent users from entering pseudo-names like John Doe, Max Mustermann (there even is a person with that name), Abcde Fghijk or Ababa Bebebe.
// Set flash data
$this->session->set_flashdata('message_name', 'This is my message');
// After that you need to used redirect function instead of load view such as
redirect("admin/signup");
// Get Flash data on view
$this->session->flashdata('message_name');
I had no idea of how to do this, because nobody answered that time, and I found no documentation about this permission. So I found my own solution. It is worser that yours, but this is a solution anyway.
I installed busybox, that set 777 permission to /data/app (I dont care about security). Then just executed "busybox install" from app. This works, but has a big security leak. If you set permissions 777, no root required.
All of the above answers were perfectly clear and complete, but just for the record I'd like to confirm that the meaning of * and ** in python has absolutely no similarity with the meaning of similar-looking operators in C.
They are called the argument-unpacking and keyword-argument-unpacking operators.
Use ,
as format specifier:
>>> format(10000.21, ',')
'10,000.21'
Alternatively you can also use str.format
instead of format
:
>>> '{:,}'.format(10000.21)
'10,000.21'
With matplotlib.ticker.FuncFormatter
:
...
ax.get_xaxis().set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
ax2.get_xaxis().set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
fig1.show()
The Following:
.show-grid [class*="span"] {
means that all child elements of '.show-grid' with a class that CONTAINS the word 'span' in it will acquire those CSS properties.
<div class="show-grid">
<div class="span">.span</div>
<div class="span6">span6</div>
<div class="attention-span">attention</div>
<div class="spanish">spanish</div>
<div class="mariospan">mariospan</div>
<div class="espanol">espanol</div>
<div>
<div class="span">.span</div>
</div>
<p class="span">span</p>
<span class="span">I do GET HIT</span>
<span>I DO NOT GET HIT since I need a class of 'span'</span>
</div>
<div class="span">I DO NOT GET HIT since I'm outside of .show-grid</span>
All of the elements get hit except for the <span>
by itself.
In Regards to Bootstrap:
span6
: this was Bootstrap 2's scaffolding technique which divided a section into a horizontal grid, based on parts of 12. Thus span6
would have a width of 50%..col-*
classes (e.g. col-sm-6
), which also specifies a media breakpoint to handle responsiveness when the window shrinks below a certain size. Check Bootstrap 4.1 and Bootstrap 3.3.7 for more documentation. I would recommend going with a later Bootstrap nowadaysSwift 4
public extension Array where Element: Hashable {
func uniqued() -> [Element] {
var seen = Set<Element>()
return filter{ seen.insert($0).inserted }
}
}
every attempt to insert
will also return a tuple: (inserted: Bool, memberAfterInsert: Set.Element)
. See documentation.
Using the returned value helps us to avoid looping or doing any other operation.
LATE EDIT: Starting with Java 8 you should use neither java.util.Date
nor java.sql.Date
if you can at all avoid it, and instead prefer using the java.time
package (based on Joda) rather than anything else. If you're not on Java 8, here's the original response:
java.sql.Date
- when you call methods/constructors of libraries that use it (like JDBC). Not otherwise. You don't want to introduce dependencies to the database libraries for applications/modules that don't explicitly deal with JDBC.
java.util.Date
- when using libraries that use it. Otherwise, as little as possible, for several reasons:
It's mutable, which means you have to make a defensive copy of it every time you pass it to or return it from a method.
It doesn't handle dates very well, which backwards people like yours truly, think date handling classes should.
Now, because j.u.D doesn't do it's job very well, the ghastly Calendar
classes were introduced. They are also mutable, and awful to work with, and should be avoided if you don't have any choice.
There are better alternatives, like the Joda Time API (which might even make it into Java 7 and become the new official date handling API - a quick search says it won't).
If you feel it's overkill to introduce a new dependency like Joda, long
s aren't all that bad to use for timestamp fields in objects, although I myself usually wrap them in j.u.D when passing them around, for type safety and as documentation.
My answer is based on this answer: How can I get the current contents of an element in webdriver just more like copy-paste.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')
element_text = element.text
element_attribute_value = element.get_attribute('value')
print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))
element = driver.find_element_by_css_selector('.description.expand_description > p')
element_text = element.text
element_attribute_value = element.get_attribute('value')
print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))
driver.quit()
For me it worked as Kumar Jaggal but: steps 1, 2, 3, the same 4. py -m setup.py install
I would highly recommend a different approach.
It's possible if you REALLY want to do it, but it costs a lot of memory and is also slow. It might not work if you have an older phone and a big bitmap. You could just pass it as an extra, for example intent.putExtra("data", bitmap)
. A Bitmap implements Parcelable, so you can put it in an extra. Likewise, a bundle has putParcelable
.
If you want to pass it inbetween activities, I would store it in a file. That's more efficient, and less work for you. You can create private files in your data folder using MODE_PRIVATE that are not accessible to any other app.
Another alternative is to nest conditions
<ng-container *ngIf="foo === 1;else second"></ng-container>
<ng-template #second>
<ng-container *ngIf="foo === 2;else third"></ng-container>
</ng-template>
<ng-template #third></ng-template>
some people talk very well about PyInstaller
A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.
If you want to control the width of your data, then you could use the width
sub-specifiers in the printf
format string. Eg. :
printf("%5d", 2);
It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.
If you want complete control, you'll probably have to implement it yourself.
If you'd like to set this globally for all users of a machine, you can create the following directory and file structures:
mkdir %windir%\Sun\Java\Deployment
Create a file deployment.config with the content:
deployment.system.config=file:///c:/windows/Sun/Java/Deployment/deployment.properties
deployment.system.config.mandatory=TRUE
Create a file deployment.properties
deployment.user.security.exception.sites=C\:/WINDOWS/Sun/Java/Deployment/exception.sites
Create a file exception.sites
http://example1.com
http://example2.com/path/to/specific/directory/
Reference https://blogs.oracle.com/java-platform-group/entry/upcoming_exception_site_list_in
Assuming you're not using html5 routing, try $location.path("route")
.
This will redirect your browser to #/route
which might be what you want.
Just add style="text-align: left"
to your label.
I usually add to index changes I don't want to stash and then stash with --keep-index
option.
git add app/controllers/cart_controller.php
git stash --keep-index
git reset
Last step is optional, but usually you want it. It removes changes from index.
Warning
As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index
just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.
A much simpler solution to this problem that allows letters, numbers and words as the label is the following code. More specifically, the line of code starting with "icon:". Any string or variable could be substituted for 'k'.
for (i = 0; i < locations.length; i++)
{
k = i + 1;
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + k + '|FF0000|000000'
});
--- the locations array holds the lat and long and k is the row number for the address I was mapping. In other words if I had a 100 addresses to map my marker labels would be 1 to 100.
Way late to this post, but I've got something slightly different to say...
>> "Are email addresses case sensitive?"
Well, "It Depends..." (TM)
Some organizations actually think that's a good idea and their email servers enforce case sensitivity.
So, for those crazy places, "Yes, Emails are case sensitive."
Note: Just because a specification says you can do something does not mean it is a good idea to do so.
The principle of KISS suggests that our systems use case insensitive emails.
Whereas the Robustness principle suggests that we accept case sensitive emails.
Solution:
This would mean that if this email already exists: [email protected]
... and another user comes along and wants to use this email: [email protected]
... that our case insensitive searching logic would return a "That email already exists" error message.
Now, you have a decision to make: Is that solution adequate in your case?
If not, you could charge a convenience fee to those clients that demand support for their case sensitive emails and implement custom logic that allows the [email protected] into your system, even if [email protected] already exists.
In which case your email search/validation logic might look like something this pseudocode:
if (user.paidEmailFee) {
// case sensitive email
query = "select * from users where email LIKE ' + user.email + '"
} else {
// case insensitive email
query = "select * from users where email ILIKE ' + user.email + '"
}
This way, you are mostly enforcing case insensitivity but allowing customers to pay for this support if they are using email systems that support such nonsense.
p.s. ILIKE is a PostgreSQL keyword: http://www.postgresql.org/docs/9.2/static/functions-matching.html
Try Wireshark:
Wireshark is the world's foremost network protocol analyzer, and is the de facto (and often de jure) standard across many industries and educational institutions.
There is a bit of a learning curve but it is far and away the best tool available.
Yes, it's working:
<select name="somename" required>
<option value="">Please select</option>
<option value="one">One</option>
</select>
you have to keep first option blank.
SELECT latitude, longitude, SQRT(
POW(69.1 * (latitude - [startlat]), 2) +
POW(69.1 * ([startlng] - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM TableName HAVING distance < 25 ORDER BY distance;
where [starlat] and [startlng] is the position where to start measuring the distance.
I always convert the byte data to a Base64 encoding and then insert the image.
This is also the way that Word does it, for it's XML files (not that Word is a good example on how to work with XML :P).
As others have said you definitely want to call Dispose
if the class implements IDisposable
. I take a fairly rigid position on this. Some might claim that calling Dispose
on DataSet
, for example, is pointless because they disassembled it and saw that it did not do anything meaningful. But, I think there are fallacies abound in that argument.
Read this for an interesting debate by respected individuals on the subject. Then read my reasoning here why I think Jeffery Richter is in the wrong camp.
Now, on to whether or not you should set a reference to null
. The answer is no. Let me illustrate my point with the following code.
public static void Main()
{
Object a = new Object();
Console.WriteLine("object created");
DoSomething(a);
Console.WriteLine("object used");
a = null;
Console.WriteLine("reference set to null");
}
So when do you think the object referenced by a
is eligible for collection? If you said after the call to a = null
then you are wrong. If you said after the Main
method completes then you are also wrong. The correct answer is that it is eligible for collection sometime during the call to DoSomething
. That is right. It is eligible before the reference is set to null
and perhaps even before the call to DoSomething
completes. That is because the JIT compiler can recognize when object references are no longer dereferenced even if they are still rooted.
Here is an algorithm in R, in case anyone needs to avoid loading additional libraries like I had to.
permutations <- function(n){
if(n==1){
return(matrix(1))
} else {
sp <- permutations(n-1)
p <- nrow(sp)
A <- matrix(nrow=n*p,ncol=n)
for(i in 1:n){
A[(i-1)*p+1:p,] <- cbind(i,sp+(sp>=i))
}
return(A)
}
}
Example usage:
> matrix(letters[permutations(3)],ncol=3)
[,1] [,2] [,3]
[1,] "a" "b" "c"
[2,] "a" "c" "b"
[3,] "b" "a" "c"
[4,] "b" "c" "a"
[5,] "c" "a" "b"
[6,] "c" "b" "a"
In my case, Logcat is showing in Android Project but not in Flutter Project.
In Flutter project, click on “Event Log” tab
it will show
23/03/20
6:52 Frameworks Detected
Android framework is detected.
click “Configure”, and it will show logcat
UPDATE:
compile 'com.android.volley:volley:1.0.0'
OLD ANSWER: You need the next in your build.gradle of your app module:
dependencies {
compile 'com.mcxiaoke.volley:library:1.0.19'
(Rest of your dependencies)
}
This is not the official repo but is a highly trusted one.
function removeParamInAddressBar(parameter) {
var url = document.location.href;
var urlparts = url.split('?');
if (urlparts.length >= 2) {
var urlBase = urlparts.shift();
var queryString = urlparts.join("?");
var prefix = encodeURIComponent(parameter) + '=';
var pars = queryString.split(/[&;]/g);
for (var i = pars.length; i-- > 0;) {
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
if (pars.length == 0) {
url = urlBase;
} else {
url = urlBase + '?' + pars.join('&');
}
window.history.pushState('', document.title, url); // push the new url in address bar
}
return url;
}
I think you can create a simple SQL query:
$sql="select username from user where id in (select id from idtables)";
$query=$this->db->query($sql);
and then you can use it normally.
All user installed apks are located in /data/app/, but you can only access this if you are rooted(afaik, you can try without root and if it doesn't work, rooting isn't hard. I suggest you search xda-developers for rooting instructions)
Use Root explorer or ES File Explorer to access /data/app/ (you have to keep going "up" until you reach the root directory /, kind of like C: in windows, before you can see the data directory(folder)). In ES file explorer you must also tick a checkbox in settings to allow going up to the root directory.
When you are in there you will see all your applications apks, though they might be named strangely. Just copy the wanted .apk and paste in the sd card, after that you can copy it to your computer and when you want to install it just open the .apk in a file manager (be sure to have install from unknown sources enabled in android settings). Even if you only want to send over bluetooth I would recommend copying it to the SD first.
PS Note that paid apps probably won't work being copied this way, since they usually check their licence online. PPS Installing an app this way may not link it with google play(you won't see it in my apps and it won't get updates).
pids=$(pgrep <name>)
will get you the pids of all processes with the given name. To kill them all, use
kill -9 $pids
To refrain from using a variable and directly kill all processes with a given name issue
pkill -9 <name>
div {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
height: 50px;_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
<label for='name'>Name:</label>_x000D_
<input type='text' id='name' />_x000D_
</div>
_x000D_
The advantages of this method is that you can change the height of the div
, change the height of the text field and change the font size and everything will always stay in the middle.
In the specific case of x68 to x68_64, the 64 bit program will be about the same size, if not slightly smaller, use a bit more memory, and run faster. Mostly this is because x86_64 doesn't just have 64 bit registers, it also has twice as many. x86 does not have enough registers to make compiled languages as efficient as they could be, so x86 code spends a lot of instructions and memory bandwidth shifting data back and forth between registers and memory. x86_64 has much less of that, and so it takes a little less space and runs faster. Floating point and bit-twiddling vector instructions are also much more efficient in x86_64.
In general, though, 64 bit code is not necessarily any faster, and is usually larger, both for code and memory usage at runtime.
I ran across this issue today working with a clients program. The program works FINE in VS6.0 using the following: (I've changed it slightly)
//
// This is the one include file that every user-written Nextest programs needs.
// Patcom-generated files will also look for this file.
//
#include "stdio.h"
#define IS_NONE( a_key ) ( ( a_key == "none" || a_key == "N/A" ) ? TRUE : FALSE )
//
// Note in my environment we have output() which is printf which adds /n at the end
//
main {
char *psNameNone = "none";
char *psNameNA = "N/A";
char *psNameCAT = "CAT";
if (IS_NONE(psNameNone) ) {
output("psNameNone Matches NONE");
output("%s psNameNoneAddr 0x%x \"none\" addr 0x%X",
psNameNone,psNameNone,
"none");
} else {
output("psNameNone Does Not Match None");
output("%s psNameNoneAddr 0x%x \"none\" addr 0x%X",
psNameNone,psNameNone,
"none");
}
if (IS_NONE(psNameNA) ) {
output("psNameNA Matches N/A");
output("%s psNameNA 0x%x \"N/A\" addr 0x%X",
psNameNA,psNameNA,
"N/A");
} else {
output("psNameNone Does Not Match N/A");
output("%s psNameNA 0x%x \"N/A\" addr 0x%X",
psNameNA,psNameNA,
"N/A");
}
if (IS_NONE(psNameCAT)) {
output("psNameNA Matches CAT");
output("%s psNameNA 0x%x \"CAT\" addr 0x%X",
psNameNone,psNameNone,
"CAT");
} else {
output("psNameNA does not match CAT");
output("%s psNameNA 0x%x \"CAT\" addr 0x%X",
psNameNone,psNameNone,
"CAT");
}
}
If built in VS6.0 with Program Database with Edit and Continue. The compares APPEAR to work. With this setting STRING pooling is enabled, and the compiler optimizes all STRING pointers to POINT TO THE SAME ADDRESSS, so this can work. Any strings created on the fly after compile time will have DIFFERENT addresses so will fail the compare. Changing the setting to Program Database only will build the program so that it will fail.
Update 2018
This is becoming quite a popular question and my answer (although marked as correct) is no longer valid. Please refer to Deepali's answer below:
npm init
Original Outdated Answer
I think you forgot to setup the directory for express:
express <yourdirectory>
Once you do that you should be able to see a bunch of files, you should then run the command:
npm install -d
Regards.
You have to explicitly cast the string types to the same in order to concatenate them, In your case you may solve the issue by simply addig an 'N' in front of 'SomeText' (N'SomeText'). If that doesn't work, try Cast('SomeText' as nvarchar(8)).
I have been toying with this as well. I initially had it in my documents folder, but decided that didn't make 'philosophical' sense. I decided to create an Android directory in my home folder and place Eclipse and the Android SKK in there.
Can also use here document and vi, the below script generates a FILE.txt with 3 lines and variable interpolation
VAR=Test
vi FILE.txt <<EOFXX
i
#This is my var in text file
var = $VAR
#Thats end of text file
^[
ZZ
EOFXX
Then file will have 3 lines as below. "i" is to start vi insert mode and similarly to close the file with Esc and ZZ.
#This is my var in text file
var = Test
#Thats end of text file
You can also make use of RenderSection , it helps to you to inject your Model
data into the _Layout
view.
You can inject View Model
Data, Json
, Script
, CSS
, HTML
etc
In this example I am injecting Json
from my Index
View to Layout
View.
Index.chtml
@section commonLayoutData{
<script>
var products = @Html.Raw(Json.Encode(Model.ToList()));
</script>
}
_Layout.cshtml
@RenderSection("commonLayoutData", false)
This eliminates the need of creating a separate Base View Model
.
Hope helps someone.
I think you can't. The SELECT element is rendered at a point beyond the reach of CSS and HTML. Is it grayed out?
But you can try to add a "size" atribute.
A Simple solution :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="-1dp"
android:left="-1dp"
android:right="-1dp"
android:top="-1dp">
<shape android:shape="rectangle">
<solid android:color="#AARRGGBB" />
<stroke
android:width="5dp"
android:color="@android:color/red"
android:dashWidth="10dp"
android:dashGap="12dp" />
</shape>
</item>
</layer-list>
And finally we have something like that :)
Simply Try this:
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));
Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:
textView.setTextColor(getResources().getColor(R.color.some_color));
Please note that from API 23, getResources().getColor()
is deprecated. Use instead:
textView.setTextColor(ContextCompat.getColor(context, R.color.some_color));
where the required color is defined in an xml as:
<resources>
<color name="some_color">#bdbdbd</color>
</resources>
Update:
This method was deprecated in API level 23. Use getColor(int, Theme) instead.
Check this.
I also ran into the same compiler error. Just a slight shorter variation of Sly_cardinal's approach.
var color: Color = Color[<string>colorId];
Create an XML file named border.xml in the drawable folder and put the following code in it.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp" android:right="5dp" android:top="5dp" >
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
Then add a background to your linear layout like this:
android:background="@drawable/border"
EDIT :
This XML was tested with a galaxy s running GingerBread 2.3.3 and ran perfectly as shown in image below:
ALSO
tested with galaxy s 3 running JellyBean 4.1.2 and ran perfectly as shown in image below :
Finally its works perfectly with all APIs
EDIT 2 :
It can also be done using a stroke to keep the background as transparent while still keeping a border except at the bottom with the following code.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:left="0dp" android:right="0dp" android:top="0dp"
android:bottom="-10dp">
<shape android:shape="rectangle">
<stroke android:width="10dp" android:color="#B22222" />
</shape>
</item>
</layer-list>
hope this help .
You can import a csv file to this website(https://www.tablesgenerator.com/latex_tables) and click copy to clipboard.
If you are using chrome: try open chrome with the args to disable web security like you see here:
If you're using local workspaces (TFS 2012+) you can now use the .tfignore
file to exclude local folders and files from being checked in.
If you add that file to source control you can ensure others on your team share the same exclusion settings.
Full details on MSDN - http://msdn.microsoft.com/en-us/library/ms245454.aspx#tfignore
For the lazy:
You can configure which kinds of files are ignored by placing a text file called
.tfignore
in the folder where you want rules to apply. The effects of the.tfignore
file are recursive. However, you can create .tfignore files in sub-folders to override the effects of a.tfignore
file in a parent folder.The following rules apply to a .tfignore file:
#
begins a comment line- The * and ? wildcards are supported.
- A filespec is recursive unless prefixed by the \ character.
- ! negates a filespec (files that match the pattern are not ignored)
Example file:
# Ignore .cpp files in the ProjA sub-folder and all its subfolders
ProjA\*.cpp
#
# Ignore .txt files in this folder
\*.txt
#
# Ignore .xml files in this folder and all its sub-folders
*.xml
#
# Ignore all files in the Temp sub-folder
\Temp
#
# Do not ignore .dll files in this folder nor in any of its sub-folders
!*.dll
The output looks correct to me:
Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1
I think Invalid Javascript code: ..
is the start of the exception message.
Normally the stacktrace isn't returned with the message:
try {
throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
System.out.println(e.getMessage()); // prints "hu?"
}
So maybe the code you are calling catches an exception and rethrows a ScriptException
. In this case maybe e.getCause().getMessage()
can help you.
Startup.cs
add this service
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
Code
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{
var id = HttpContextAccessor.HttpContext.Request.RouteValues["id"];
if (id != null)
{
// parameter exist in your URL
}
string navigation = await Navigation.WebNavigation(activeTab);
}
Structure packing is only done when you tell your compiler explicitly to pack the structure. Padding is what you're seeing. Your 32-bit system is padding each field to word alignment. If you had told your compiler to pack the structures, they'd be 6 and 5 bytes, respectively. Don't do that though. It's not portable and makes compilers generate much slower (and sometimes even buggy) code.
GRANT ALL PRIVILEGES ON mydb.* TO myuser@localhost IDENTIFIED BY 'mypasswd';
Works for privileges on schema :)
Optional: after mypasswd
you can add WITH GRANT OPTION
String.prototype.replaceArray = function (find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
// global replacement
var pos = replaceString.indexOf(find[i]);
while (pos > -1) {
replaceString = replaceString.replace(find[i], replace[i]);
pos = replaceString.indexOf(find[i]);
}
}
return replaceString;
};
var textT = "Hello world,,,,, hello people.....";
var find = [".",","];
var replace = ['2', '5'];
textT = textT.replaceArray(find, replace);
// result: Hello world55555 hello people22222
If I understand your problem correctly, you are trying to restore (transact sql) xyz.sql - database + schema. You can try this command which worked for me:
SQLCMD -U sa -i xyz.sql
This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.
This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.
public class HexColor
{
public static void main (String[] args)
{
JSlider sRed = new JSlider(0,255,1);
JSlider sGreen = new JSlider(0,255,1);
JSlider sBlue = new JSlider(0,255,1);
JLabel hexCode = new JLabel();
JPanel myPanel = new JPanel();
GridBagLayout layout = new GridBagLayout();
JFrame frame = new JFrame();
//set frame to organize components using GridBagLayout
frame.setLayout(layout);
//create gray filled rectangle
myPanel.paintComponent();
myPanel.setBackground(Color.GRAY);
//In practice this code is replicated and applied to sGreen and sBlue.
//For the sake of brevity I only show sRed in this post.
sRed.addChangeListener(
new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e){
myPanel.setBackground(changeColor());
myPanel.repaint();
hexCode.setText(toHex());
}
}
);
//add each component to JFrame
frame.add(myPanel);
frame.add(sRed);
frame.add(sGreen);
frame.add(sBlue);
frame.add(hexCode);
} //end of main
//creates JPanel filled rectangle
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(360, 300, 10, 10);
g.fillRect(360, 300, 10, 10);
}
//changes the display color in JPanel
private Color changeColor()
{
int r = sRed.getValue();
int b = sBlue.getValue();
int g = sGreen.getValue();
Color c;
return c = new Color(r,g,b);
}
//Displays hex representation of displayed color
private String toHex()
{
Integer r = sRed.getValue();
Integer g = sGreen.getValue();
Integer b = sBlue.getValue();
Color hC;
hC = new Color(r,g,b);
String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
while(hex.length() < 6){
hex = "0" + hex;
}
hex = "Hex Code: #" + hex;
return hex;
}
}
A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.
Sorry for being lazy just providing solution without explaining the reason. Now I'm updating my answer.
Reason: This error occurs because jackson library
doesn't know how to create your model which doesn't have empty constructor
and the model contains constructor with parameters which didn't annotated its parameters with @JsonProperty("field_name")
. By default java compiler creates empty constructor if you didn't add constructor to your class.
Solution:
Add empty constructor
to your model or annotate constructor parameters with @JsonProperty("field_name")
If you use kotlin data class
then also can annotate with @JsonProperty("field_name")
or register jackson module kotlin to ObjectMapper
.
You can create your models using http://www.jsonschema2pojo.org/.
I just ran into this myself since I'm trying to create myself a bare bones framework but started out by creating a new Win32 Program option in Visual Studio 2017. "stdafx.h" is unnecessary and should be removed. Then you can remove the stupid "stdafx.h" and "stdafx.cpp" that is in your Solution Explorer as well as the files from your project. In it's place, you'll need to put
#include <Windows.h>
instead.
If you are simply looking for producing a binary executable from a PHP script, then please avoid trying to make your question extremely precise because it will make it appear that you know exactly what you need. Besides, most PHP developer have absolutely zero clue about what a bytecode is.
With that said, the answers is YES. I have just finished compiling a PHP script into a binary. And not just any binary. I have used the CDE application (link to Wayback Machine, the original link is now broken) to turn it into an portable binary that can be distributed with all the dependencies and executed without any issue… and it works beautifully.
All you need is to use phc.
While looking at your code, the only thing I see wrong, is when you try to load the second database:
$DB2=$this->load->database($config);
When you want to retrieve the database object, you have to pass TRUE in the second argument.
From the Codeigniter User Guide:
By setting the second parameter to TRUE (boolean) the function will return the database object.
So, your code should instead be:
$DB2=$this->load->database($config, TRUE);
That will make it work.
In plain Javascript, you could use Array#reduce
with an object
var cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }],_x000D_
result = cars.reduce(function (r, a) {_x000D_
r[a.make] = r[a.make] || [];_x000D_
r[a.make].push(a);_x000D_
return r;_x000D_
}, Object.create(null));_x000D_
_x000D_
console.log(result);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
There's my method to multiple upload file:
Nodejs :
router.post('/upload', function(req , res) {
var multiparty = require('multiparty');
var form = new multiparty.Form();
var fs = require('fs');
form.parse(req, function(err, fields, files) {
var imgArray = files.imatges;
for (var i = 0; i < imgArray.length; i++) {
var newPath = './public/uploads/'+fields.imgName+'/';
var singleImg = imgArray[i];
newPath+= singleImg.originalFilename;
readAndWriteFile(singleImg, newPath);
}
res.send("File uploaded to: " + newPath);
});
function readAndWriteFile(singleImg, newPath) {
fs.readFile(singleImg.path , function(err,data) {
fs.writeFile(newPath,data, function(err) {
if (err) console.log('ERRRRRR!! :'+err);
console.log('Fitxer: '+singleImg.originalFilename +' - '+ newPath);
})
})
}
})
Make sure your form has enctype="multipart/form-data"
I hope this gives you a hand ;)
In my case the reason was, I only forgot the closing
</script>
tag.
But that caused the same error message.
Nullable type can invoke runtime error.
So I think it's good to use a compiler option --strictNullChecks
and declare number | null
as type. also in case of nested function, although input type is null, compiler can not know what it could break, so I recommend use !
(exclamination mark).
function broken(name: string | null): string {
function postfix(epithet: string) {
return name.charAt(0) + '. the ' + epithet; // error, 'name' is possibly null
}
name = name || "Bob";
return postfix("great");
}
function fixed(name: string | null): string {
function postfix(epithet: string) {
return name!.charAt(0) + '. the ' + epithet; // ok
}
name = name || "Bob";
return postfix("great");
}
Reference. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions