make_unique
is an upcoming C++14 feature and thus might not be available on your compiler, even if it is C++11 compliant.
You can however easily roll your own implementation:
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
(FYI, here is the final version of make_unique
that was voted into C++14. This includes additional functions to cover arrays, but the general idea is still the same.)
Because userString is empty. You only declare it
vector<string> userString;
but never add anything, so the for loop won't even run.
import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);
Update
According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.
Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences
method of the Context
class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.
(1) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
(2) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE
is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
. In MODE_WORLD_READABLE
other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE
other applications also have write permissions for the created file.
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor
object has to be used. Editor
is a nested interface in the SharedPreference
class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also supports methods like remove()
and clear()
to delete the preference values from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences()
method of the activity. The getPreference
method uses the getSharedPreferences()
method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also the same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference
. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
nflog is better
sudo apt-get -y install ulogd2
ICMP Block rule example:
iptables=/sbin/iptables
# Drop ICMP (PING)
$iptables -t mangle -A PREROUTING -p icmp -j NFLOG --nflog-prefix 'ICMP Block'
$iptables -t mangle -A PREROUTING -p icmp -j DROP
And you can search prefix "ICMP Block" in log:
/var/log/ulog/syslogemu.log
If you've already installed Android Studio --
Add the following lines to the end of ~/.bashrc
or ~/.zshrc
(if using Oh My ZSH):
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Restart Terminal and you're good to go.
Use this
DELETE FROM `articles`, `comments`
USING `articles`,`comments`
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
or
DELETE `articles`, `comments`
FROM `articles`, `comments`
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
The str.split()
method without an argument splits on whitespace:
>>> "many fancy word \nhello \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']
To append to an array, just use the +=
operator.
$Target += $TargetObject
Also, you need to declare $Target = @()
before your loop because otherwise, it will empty the array every loop.
I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync
. I tried both cygwin
and minGW
. It seems like rsync
is incompatible with git for windows
's version of ssh
.
Here is what worked for me: NFS.
Vagrant docs says:
NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.
This isn't true anymore. We can use vagrant-winnfsd
plugin nowadays. It's really simple to install:
vagrant plugin install vagrant-winnfsd
Vagrantfile
: config.vm.synced_folder ".", "/vagrant", type: "nfs"
Vagrantfile
: config.vm.network "private_network", type: "dhcp"
That's all I needed to make NFS
work. Laravel response time decreased from 500ms to 100ms for me.
just use a subquery right there like:
INSERT INTO table1 VALUES ("A string", 5, (SELECT ...)).
You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub
If it is just viewing in tree view,One workaround is to use the Explorer in Notepad++ or any other tools.
Do not include the '.exe' in your file path.
For example:
from selenium import webdriver
driver = webdriver.Chrome(executable_path='path/to/folder/chromedriver')
1st way is to use props
<Row id = "someRandomID">
Wherein, in the Definition, you may just go
const Row = props => {
div id = {props.id}
}
The same could be done with class, replacing id with className in the above example.
You might as well use react-html-id
, that is an npm package.
This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.
Ref: react-html-id
Peace.
This is a possible generic implementation using a bit of reflection (pseudo-code, don't have VS now):
public class DtoMapper<DtoType>
{
Dictionary<string,PropertyInfo> properties;
public DtoMapper()
{
// Cache property infos
var t = typeof(DtoType);
properties = t.GetProperties().ToDictionary(p => p.Name, p => p);
}
public DtoType Map(Dto dto)
{
var instance = Activator.CreateInstance(typeOf(DtoType));
foreach(var p in properties)
{
p.SetProperty(
instance,
Convert.Type(
p.PropertyType,
dto.Items[Array.IndexOf(dto.ItemsNames, p.Name)]);
return instance;
}
}
Usage:
var mapper = new DtoMapper<Model>();
var modelInstance = mapper.Map(dto);
This will be slow when you create the mapper instance but much faster later.
A linq-to-sql query isn't executed as code, but rather translated into SQL. Sometimes this is a "leaky abstraction" that yields unexpected behaviour.
One such case is null handling, where there can be unexpected nulls in different places. ...DefaultIfEmpty(0).Sum(0)
can help in this (quite simple) case, where there might be no elements and sql's SUM
returns null
whereas c# expect 0.
A more general approach is to use ??
which will be translated to COALESCE
whenever there is a risk that the generated SQL returns an unexpected null:
var creditsSum = (from u in context.User
join ch in context.CreditHistory on u.ID equals ch.UserID
where u.ID == userID
select (int?)ch.Amount).Sum() ?? 0;
This first casts to int?
to tell the C# compiler that this expression can indeed return null
, even though Sum()
returns an int
. Then we use the normal ??
operator to handle the null
case.
Based on this answer, I wrote a blog post with details for both LINQ to SQL and LINQ to Entities.
Anatoliy's answer in PHP:
public static function detectCardType($num)
{
$re = array(
"visa" => "/^4[0-9]{12}(?:[0-9]{3})?$/",
"mastercard" => "/^5[1-5][0-9]{14}$/",
"amex" => "/^3[47][0-9]{13}$/",
"discover" => "/^6(?:011|5[0-9]{2})[0-9]{12}$/",
);
if (preg_match($re['visa'],$num))
{
return 'visa';
}
else if (preg_match($re['mastercard'],$num))
{
return 'mastercard';
}
else if (preg_match($re['amex'],$num))
{
return 'amex';
}
else if (preg_match($re['discover'],$num))
{
return 'discover';
}
else
{
return false;
}
}
For me the answer was that I was passing two parameters to and execute SQL task, but only using one. I was doing some testing and commented out a section of code using the second parameter. I neglected to remove the parameter mapping.
So ensure you are passing in the correct number of parameters in the parameter mapping if you are using the Execute SQL task.
I have had the same problem with anaconda on windows. It seems that there is an issu with mcAfee antivirus. If you deactivate it while running the updates or the installs, it allows you to properly run the installation.
Found a faster method:
$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
10000000 loops, best of 3: 0.222 usec per loop
$ python -m timeit -s "from random import random" "True if random() > 0.5 else False"
10000000 loops, best of 3: 0.0786 usec per loop
$ python -m timeit -s "from random import random" "random() > 0.5"
10000000 loops, best of 3: 0.0579 usec per loop
For checking complete changes:
git diff <commit_Id_1> <commit_Id_2>
For checking only the changed/added/deleted files:
git diff <commit_Id_1> <commit_Id_2> --name-only
NOTE: For checking diff without commit in between, you don't need to put the commit ids.
You code is correct. replace items with .items as below
<script>
var n = $(".items").css("left");
if(n == -900){
$(".items span").fadeOut("slow");
}
</script>
If your working tree is dirty, you can compare it to a stash by first committing the dirty working tree, and then comparing it to the stash. Afterwards, you may undo the commit with the dirty working tree (since you might not want to have that dirty commit in your commit log).
You can also use the following approach to compare two stashes with each other (in which case you just pop one of the stashes at first).
Commit your dirty working tree:
git add .
git commit -m "Dirty commit"
Diff the stash with that commit:
git diff HEAD stash@{0}
Then, afterwards, you may revert the commit, and put it back in the working dir:
git reset --soft HEAD~1
git reset .
Now you've diffed the dirty working tree with your stash, and are back to where you were initially.
Prefix the call with Module2 (ex. Module2.IDLE
). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.
Complete tutorial here
Demo link
JavaScript
$('.owl-carousel').owlCarousel({
margin: 10,
nav: true,
navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
responsive: {
0: {
items: 1
},
600: {
items: 3
},
1000: {
items: 5
}
}
});
CSS Style for navigation
.owl-carousel .nav-btn{
height: 47px;
position: absolute;
width: 26px;
cursor: pointer;
top: 100px !important;
}
.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}
.owl-carousel .prev-slide{
background: url(nav-icon.png) no-repeat scroll 0 0;
left: -33px;
}
.owl-carousel .next-slide{
background: url(nav-icon.png) no-repeat scroll -24px 0px;
right: -33px;
}
.owl-carousel .prev-slide:hover{
background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}
use
$("#mySelectBox option:selected");
to test if its a particular option myoption
:
if($("#mySelectBox option:selected").text() == myoption){
//...
}
simple way,
import re
str = 'this is string ! >><< (foo---> bar) @-tuna-# sandwich-%-is-$-* good'
// condense multiple empty spaces into 1
str = ' '.join(str.split()
// replace empty space with dash
str = str.replace(" ","-")
// take out any char that matches regex
str = re.sub('[!@#$%^&*()_+<>]', '', str)
output:
this-is-string--foo----bar--tuna---sandwich--is---good
And for Windows 8.1/10 OS Users just open cmd (command prompt)
write this : C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36-32\Scripts
then
just write this : pip3 install
{name of package}
Hint: the location of folder Python36-32
may get different for new python 3.x versions
You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task
or Task<T>
, if you return nothing and you want your method will be run asyncronously you should define your method like this:
private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); }
And in Main method you can't await for DoDownloadAsync
, because you can't use await keyword in non-async function, and you can't make Main
async. So consider this:
var result = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); result.Wait();
List<Customer> list = ...;
Customer john = list.SingleOrDefault(customer => customer.Firstname == "John");
john will be null if no customer exists with a first name of "John".
It is because you are in a try
statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally
block, that way it will for sure be returned.
Make sure that you initialize sum outside the try/catch/finally
so that it is in scope.
Add authenticity_token: true
to the form tag
You need to git push -f
assuming that nobody has pulled the other commit before. Beware, you're changing history.
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
I got a similar error (Incorrect string value: '\xD0\xBE\xDO\xB2. ...' for 'content' at row 1
). I have tried to change character set of column to utf8mb4
and after that the error has changed to 'Data too long for column 'content' at row 1'
.
It turned out that mysql shows me wrong error. I turned back character set of column to utf8
and changed type of the column to MEDIUMTEXT
. After that the error disappeared.
I hope it helps someone.
By the way MariaDB in same case (I have tested the same INSERT there) just cut a text without error.
$(document).ready(function () {
$("#tbl_Customer tbody tr .companyname").click(function () {
var comapnyname = $(this).closest(".trclass").find(".companyname").text();
var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
// var clickedCell = $(this);
alert(comapnyname);
alert(CompanyAddress);
alert(CompanyEmail);
alert(CompanyContactNumber);
alert(CompanyContactPerson);
//alert(clickedCell.text());
});
});
Instead of using onload, use Angular's ng-init
.
<article id="showSelector" ng-controller="CinemaCtrl" ng-init="myFunction()">
Note: This requires that myFunction is a property of the CinemaCtrl
scope.
This is how i do it.
$("input[name='title']").on({
"change keyup": function(e) {
var slug = $(this).val().split(" ").join("-").toLowerCase();
$("input[name='slug']").val(slug);
},
});
For those who like to reduce typing (i.e., everyone!): pd.set_option('max_colwidth', None)
does the same thing
For the non-selected radio buttons, flag them as disabled. This prevents them from responding to user input and clearing out the checked radio button. For example:
<input type="radio" name="var" checked="yes" value="Yes"></input>
<input type="radio" name="var" disabled="yes" value="No"></input>
The basic answer is, yes it is undefined.
If you are seeing odd behavior because of this, it may depended on where it is declared. If within a function on the stack then the contents will more than likely be different every time the function gets called. If it is a static or module scope it is undefined but will not change.
In your particular example perhaps you do not have to perform any checks at all. Is that possible that New-Object
return null? I have never seen that. The command should fail in case of a problem and the rest of the code in the example will not be executed. So why should we do that checks at all?
Only in the code like below we need some checks (explicit comparison with $null is the best):
# we just try to get a new object
$ie = $null
try {
$ie = New-Object -ComObject InternetExplorer.Application
}
catch {
Write-Warning $_
}
# check and continuation
if ($ie -ne $null) {
...
}
I prefer to clip rather than drop. the following will clip inplace at the 2nd and 98th pecentiles.
df_list = list(df)
minPercentile = 0.02
maxPercentile = 0.98
for _ in range(numCols):
df[df_list[_]] = df[df_list[_]].clip((df[df_list[_]].quantile(minPercentile)),(df[df_list[_]].quantile(maxPercentile)))
What works best for me is using quote()
and eval()
together.
For example, let's print each column using a for loop
:
Columns <- names(dat)
for (i in 1:ncol(dat)){
dat[, eval(quote(Columns[i]))] %>% print
}
In a php section before the HTML section, use sprinf() to create a constant string from the variables:
$mystuff = sprinf("My name is %s and my mother's name is %s","Suzy","Caroline");
Then in the HTML section you can do whatever you like, such as:
<p>$mystuff</p>
For int and long, as primitives, not really. For Integer, it is possible someone wrote one.
Given that BigInteger is a (mathematical/functional) superset of int, Integer, long, and Long, if you need to use these types, convert them to a BigInteger, do the GCD, and convert the result back.
private static int gcdThing(int a, int b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
So I had a lot of problems with all of the solutions mentioned so far...
I have a local package that I want to always reference (rather than npm link) because it won't be used outside of this project (for now) and also won't be uploaded to an npm repository for wide use as of yet.
I also need it to work on Windows AND Unix, so sym-links aren't ideal.
Pointing to the tar.gz result of (npm package) works for the dependent npm package folder, however this causes issues with the npm cache if you want to update the package. It doesn't always pull in the new one from the referenced npm package when you update it, even if you blow away node_modules and re-do your npm-install for your main project.
so.. This is what worked well for me!
Main Project's Package.json File Snippet:
"name": "main-project-name",
"version": "0.0.0",
"scripts": {
"ng": "ng",
...
"preinstall": "cd ../some-npm-package-angular && npm install && npm run build"
},
"private": true,
"dependencies": {
...
"@com/some-npm-package-angular": "file:../some-npm-package-angular/dist",
...
}
This achieves 3 things:
I hope this is clear, and helps someone out.
The tar.gz approach also sort of works..
npm install (file path) also sort of works.
This was all based off of a generated client from an openapi spec that we wanted to keep in a separate location (rather than using copy-pasta for individual files)
====== UPDATE: ======
There are additional errors with a regular development flow with the above solution, as npm's versioning scheme with local files is absolutely terrible. If your dependent package changes frequently, this whole scheme breaks because npm will cache your last version of the project and then blow up when the SHA hash doesn't match anymore with what was saved in your package-lock.json file, among other issues.
As a result, I recommend using the *.tgz approach with a version update for each change. This works by doing three things.
First:
For your dependent package, use the npm library "ng-packagr". This is automatically added to auto-generated client packages created by the angular-typescript code generator for OpenAPI 3.0.
As a result the project that I'm referencing has a "scripts" section within package.json that looks like this:
"scripts": {
"build": "ng-packagr -p ng-package.json",
"package": "npm install && npm run build && cd dist && npm pack"
},
And the project referencing this other project adds a pre-install step to make sure the dependent project is up to date and rebuilt before building itself:
"scripts": {
"preinstall": "npm run clean && cd ../some-npm-package-angular && npm run package"
},
Second
Reference the built tgz npm package from your main project!
"dependencies": {
"@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-<packageVersion>.tgz",
...
}
Third
Update the dependent package's version EVERY TIME you update the dependent package. You'll also have to update the version in the main project.
If you do not do this, NPM will choke and use a cached version and explode when the SHA hash doesn't match. NPM versions file-based packages based on the filename changing. It won't check the package itself for an updated version in package.json, and the NPM team stated that they will not fix this, but people keep raising the issue: https://github.com/microsoft/WSL/issues/348
for now, just update the:
"version": "1.0.0-build5",
In the dependent package's package.json file, then update your reference to it in the main project to reference the new filename, ex:
"dependencies": {
"@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-1.0.0-build5.tgz",
...
}
You get used to it. Just update the two package.json files - version then the ref to the new filename.
Hope that helps someone...
The JVM is caching Integer values. Hence the comparison with ==
only works for numbers between -128 and 127.
When importing csv data files the import command should reflect both the data seperation between each column (;) and the float-number seperator for your numeric values (for numerical variable = 2,5 this would be ",").
The command for importing a csv, therefore, has to be a bit more comprehensive with more commands:
stuckey <- read.csv2("C:/kalle/R/stuckey.csv", header=TRUE, sep=";", dec=",")
This should import all variables as either integers or numeric.
You should use something similar to this for adding TextView to LinearLayout dynamically:
LinearLayout linearLayout = getActivity().findViewById(R.id.infoLayout);
TextView valueTV = new TextView(context);
valueTV.setText("hallo hallo");
valueTV.setId(Integer.parseInt("5"));
valueTV.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(valueTV);
getActivity() is used for inside Fragments, you can use context or anything similar per each instance you are inside.
simply,
select sysdate-1 from dual
there's a bunch more info and detail here: http://www.orafaq.com/faq/how_does_one_add_a_day_hour_minute_second_to_a_date_value
header("Location: route_to_main_page");
I've encountered this problem while having a custom 404 error handling file. Instead of throwing some html content it was suppose to redirect to the main page url. It worked well.
Then I used this as a skeleton for a next project, therefore not changing the "route_to_main_page" actually on the new project (different URL) became a "route_to_external_url" so any 404 errors within your code (missing css stylesheets, js libraries) would return the "Uncaught SyntaxError: Unexpected token <".
There is another way which ignores all empty cells before a nonempty cell and selects the last empty cell from the end of the first column. Columns should be addressed with their number eg. Col "A" = 1.
With ThisWorkbook.Sheets("sheet1")
.Cells(.Cells(.Cells.Rows.Count, 1).End(xlUp).Row + 1, 1).select
End With
The next code is exactly as the above but can be understood better.
i = ThisWorkbook.Sheets("sheet1").Cells.Rows.Count
j = ThisWorkbook.Sheets("sheet1").Cells(i, 1).End(xlUp).Row
ThisWorkbook.Sheets("sheet1").Cells(j + 1, 1) = textbox1.value
following script will use to create any kind of file, with user input as extension
import sys
def create():
print("creating new file")
name=raw_input ("enter the name of file:")
extension=raw_input ("enter extension of file:")
try:
name=name+"."+extension
file=open(name,'a')
file.close()
except:
print("error occured")
sys.exit(0)
create()
In newer versions of Git for Windows, Bash is started with --login
which causes Bash to not read .bashrc
directly. Instead it reads .bash_profile
.
If this file does not exist, create it with the following content:
if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
This will cause Bash to read the .bashrc
file. From my understanding of this issue, Git for Windows should do this automatically. However, I just installed version 2.5.1, and it did not.
Just multiply the number by 100, round, and divide the resulting number by 100.
You should only have one <system.web>
in your Web.Config Configuration File
.
<?xml version="1.0"?>
<configuration>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true"/>
<authentication mode="None"/>
</system.web>
</configuration>
Use cd
in a subshell; the shorthand way to use this kind of subshell is parentheses.
(cd wherever; mycommand ...)
That said, if your command has an environment that it requires, it should really ensure that environment itself instead of putting the onus on anything that might want to use it (unless it's an internal command used in very specific circumstances in the context of a well defined larger system, such that any caller already needs to ensure the environment it requires). Usually this would be some kind of shell script wrapper.
Looks like all you need is text-align: center;
in ul
Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use
string s = Char.ConvertFromUtf32(56);
which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.
By default, Button in android provides all caps keyword. If you want button text to be in lower case or mixed case you can disable textAllCaps
flag using android:textAllCaps="false"
You also run into this issue when you are creating routine in a class module.
When you try to run the code externally, you get this error.
You can't assign macro to button to a member of a class module either.
If you try to run from within the code by pressing green play button you will also see the same error.
Either move the routine in to a regular module or create a new routine in a regular module that calls the class member.
You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.
You can do:
foreach ($arr as $key => $value) {
echo $key;
}
As described in PHP docs.
If you would need to disable E_DEPRACATED also, use:
php_value error_reporting 22527
In my case CMS Made Simple was complaining "E_STRICT is enabled in the error_reporting" as well as "E_DEPRECATED is enabled". Adding that one line to .htaccess solved both misconfigurations.
Auto resize:
For jQgrid 3.5+
if (grid = $('.ui-jqgrid-btable:visible')) {
grid.each(function(index) {
gridId = $(this).attr('id');
gridParentWidth = $('#gbox_' + gridId).parent().width();
$('#' + gridId).setGridWidth(gridParentWidth);
});
}
For jQgrid 3.4.x:
if (typeof $('table.scroll').setGridWidth == 'function') {
$('table.scroll').setGridWidth(100, true); //reset when grid is wider than container (div)
if (gridObj) {
} else {
$('#contentBox_content .grid_bdiv:reallyvisible').each(function(index) {
grid = $(this).children('table.scroll');
gridParentWidth = $(this).parent().width() – origami.grid.gridFromRight;
grid.setGridWidth(gridParentWidth, true);
});
}
}
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
This has to be done during your exe4j configuration. In the fourth step of Exe4j wizard which is Executable Info select> Advanced options select 32-bit or 64-bit. This worked well for me. or else install both JDK tool-kits x64 and x32 in your machine.
I find that clang-format
works well.
There are some example keybindings in the clang documentation
I prefer to use the equalprg
binding in vim. This allows you to invoke clang-format
with G=gg
or other =
indent options.
Just put the following in your .vimrc file:
autocmd FileType c,cpp setlocal equalprg=clang-format
Why to annoy the user with three different Dialog Boxes to enter things, why not do all this in one go in a single Dialog and save time, instead of testing the patience of the USER ?
You can add everything in a single Dialog, by putting all the fields on your JPanel
and then adding this JPanel
to your JOptionPane
. Below code can clarify a bit more :
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class AverageExample
{
private double[] marks;
private JTextField[] marksField;
private JLabel resultLabel;
public AverageExample()
{
marks = new double[3];
marksField = new JTextField[3];
marksField[0] = new JTextField(10);
marksField[1] = new JTextField(10);
marksField[2] = new JTextField(10);
}
private void displayGUI()
{
int selection = JOptionPane.showConfirmDialog(
null, getPanel(), "Input Form : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.PLAIN_MESSAGE);
if (selection == JOptionPane.OK_OPTION)
{
for ( int i = 0; i < 3; i++)
{
marks[i] = Double.valueOf(marksField[i].getText());
}
Arrays.sort(marks);
double average = (marks[1] + marks[2]) / 2.0;
JOptionPane.showMessageDialog(null
, "Average is : " + Double.toString(average)
, "Average : "
, JOptionPane.PLAIN_MESSAGE);
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
// Do something here.
}
}
private JPanel getPanel()
{
JPanel basePanel = new JPanel();
//basePanel.setLayout(new BorderLayout(5, 5));
basePanel.setOpaque(true);
basePanel.setBackground(Color.BLUE.darker());
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 2, 5, 5));
centerPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
JLabel mLabel1 = new JLabel("Enter Marks 1 : ");
JLabel mLabel2 = new JLabel("Enter Marks 2 : ");
JLabel mLabel3 = new JLabel("Enter Marks 3 : ");
centerPanel.add(mLabel1);
centerPanel.add(marksField[0]);
centerPanel.add(mLabel2);
centerPanel.add(marksField[1]);
centerPanel.add(mLabel3);
centerPanel.add(marksField[2]);
basePanel.add(centerPanel);
return basePanel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new AverageExample().displayGUI();
}
});
}
}
Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError
). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError
.
Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).
If that's not enough, consider converting to a sqlite3
database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.
If you are using Java 6 or higher you can use wildcards of this form:
java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp
If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:
java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp
There is nothing like lib\*\*
or lib\**
wildcard for the kind of job you want to be done.
Info.plist
First things first. You need to add your descriptive string in the info.plist file for the keys NSLocationWhenInUseUsageDescription
or NSLocationAlwaysUsageDescription
depending on what kind of service you are requesting
Code
import Foundation
import CoreLocation
class LocationManager: NSObject, CLLocationManagerDelegate {
let manager: CLLocationManager
var locationManagerClosures: [((userLocation: CLLocation) -> ())] = []
override init() {
self.manager = CLLocationManager()
super.init()
self.manager.delegate = self
}
//This is the main method for getting the users location and will pass back the usersLocation when it is available
func getlocationForUser(userLocationClosure: ((userLocation: CLLocation) -> ())) {
self.locationManagerClosures.append(userLocationClosure)
//First need to check if the apple device has location services availabel. (i.e. Some iTouch's don't have this enabled)
if CLLocationManager.locationServicesEnabled() {
//Then check whether the user has granted you permission to get his location
if CLLocationManager.authorizationStatus() == .NotDetermined {
//Request permission
//Note: you can also ask for .requestWhenInUseAuthorization
manager.requestWhenInUseAuthorization()
} else if CLLocationManager.authorizationStatus() == .Restricted || CLLocationManager.authorizationStatus() == .Denied {
//... Sorry for you. You can huff and puff but you are not getting any location
} else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
// This will trigger the locationManager:didUpdateLocation delegate method to get called when the next available location of the user is available
manager.startUpdatingLocation()
}
}
}
//MARK: CLLocationManager Delegate methods
@objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
manager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
//Because multiple methods might have called getlocationForUser: method there might me multiple methods that need the users location.
//These userLocation closures will have been stored in the locationManagerClosures array so now that we have the users location we can pass the users location into all of them and then reset the array.
let tempClosures = self.locationManagerClosures
for closure in tempClosures {
closure(userLocation: newLocation)
}
self.locationManagerClosures = []
}
}
Usage
self.locationManager = LocationManager()
self.locationManager.getlocationForUser { (userLocation: CLLocation) -> () in
print(userLocation)
}
When you have many HTML inputs named C[]
what you get in the POST array on the other end is an array of these values in $_POST['C']
. So when you echo
that, you are trying to print an array, so all it does is print Array
and a notice.
To print properly an array, you either loop through it and echo
each element, or you can use print_r
.
Alternatively, if you don't know if it's an array or a string or whatever, you can use var_dump($var)
which will tell you what type it is and what it's content is. Use that for debugging purposes only.
Use -C
option of tar:
tar zxvf <yourfile>.tar.gz -C /usr/src/
and then, the content of the tar should be in:
/usr/src/<yourfile>
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
This is a side note, but in idiomatic Python, you will often see things like:
if x is None:
# Some clauses
This is safe, because there is guaranteed to be one instance of the Null Object (i.e., None).
This will replace all ?
with '
:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
WHERE city LIKE '%?%'
If you need to update more than one column, you can either change city
each time you execute to a different column name, or list the columns like so:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'
Sample pagination react js working code
import React, { Component } from 'react';
import {
Pagination,
PaginationItem,
PaginationLink
} from "reactstrap";
let prev = 0;
let next = 0;
let last = 0;
let first = 0;
export default class SamplePagination extends Component {
constructor() {
super();
this.state = {
todos: ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','T','v','u','w','x','y','z'],
currentPage: 1,
todosPerPage: 3,
};
this.handleClick = this.handleClick.bind(this);
this.handleLastClick = this.handleLastClick.bind(this);
this.handleFirstClick = this.handleFirstClick.bind(this);
}
handleClick(event) {
event.preventDefault();
this.setState({
currentPage: Number(event.target.id)
});
}
handleLastClick(event) {
event.preventDefault();
this.setState({
currentPage:last
});
}
handleFirstClick(event) {
event.preventDefault();
this.setState({
currentPage:1
});
}
render() {
let { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying current todos
let indexOfLastTodo = currentPage * todosPerPage;
let indexOfFirstTodo = indexOfLastTodo - todosPerPage;
let currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);
prev = currentPage > 0 ? (currentPage -1) :0;
last = Math.ceil(todos.length/todosPerPage);
next = (last === currentPage) ?currentPage: currentPage +1;
// Logic for displaying page numbers
let pageNumbers = [];
for (let i = 1; i <=last; i++) {
pageNumbers.push(i);
}
return (
<div>
<ul>
{
currentTodos.map((todo,index) =>{
return <li key={index}>{todo}</li>;
})
}
</ul><ul id="page-numbers">
<nav>
<Pagination>
<PaginationItem>
{ prev === 0 ? <PaginationLink disabled>First</PaginationLink> :
<PaginationLink onClick={this.handleFirstClick} id={prev} href={prev}>First</PaginationLink>
}
</PaginationItem>
<PaginationItem>
{ prev === 0 ? <PaginationLink disabled>Prev</PaginationLink> :
<PaginationLink onClick={this.handleClick} id={prev} href={prev}>Prev</PaginationLink>
}
</PaginationItem>
{
pageNumbers.map((number,i) =>
<Pagination key= {i}>
<PaginationItem active = {pageNumbers[currentPage-1] === (number) ? true : false} >
<PaginationLink onClick={this.handleClick} href={number} key={number} id={number}>
{number}
</PaginationLink>
</PaginationItem>
</Pagination>
)}
<PaginationItem>
{
currentPage === last ? <PaginationLink disabled>Next</PaginationLink> :
<PaginationLink onClick={this.handleClick} id={pageNumbers[currentPage]} href={pageNumbers[currentPage]}>Next</PaginationLink>
}
</PaginationItem>
<PaginationItem>
{
currentPage === last ? <PaginationLink disabled>Last</PaginationLink> :
<PaginationLink onClick={this.handleLastClick} id={pageNumbers[currentPage]} href={pageNumbers[currentPage]}>Last</PaginationLink>
}
</PaginationItem>
</Pagination>
</nav>
</ul>
</div>
);
}
}
ReactDOM.render(
<SamplePagination />,
document.getElementById('root')
);
This is your config :
log4j.appender.FILE.File=logs/${file.name}
And this error happened :
java.io.FileNotFoundException: logs (Access is denied)
So it seems that the variable file.name
is not set, and java tries to write to the directory logs
.
You can force the value of your variable ${file.name}
calling maven with this option -D :
mvn clean test -Dfile.name=logfile.log
Getting month range with .Net API (just another way):
DateTime date = ...
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
You can try to use Prettyfox UI library http://ng.prettyfox.org
This library use bootstrap 4 styles and not need jquery.
Use log4j in your java program instead. Then you can output to multiple media, create rolling logs, etc. and include timestamps, class names and line numbers.
With Guava:
final Splitter splitter = Splitter.on("-").trimResults();
assertEquals("Günnewig Uebachs", Iterables.getLast(splitter.split(one)));
assertEquals("Madison", Iterables.getLast(splitter.split(two)));
INSERT INTO hr.employees (location_id) VALUE (1000) WHERE first_name LIKE '%D%';
let me know if there is any problem in this statement.
It's 2014 now guys, and time complexity still matters!
array.filter(function() {
var seen = {};
return function(element, index, array) {
return !(element in seen) && (seen[element] = 1);
};
}());
I already found the solution to this problem which I forgot to post here.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {
@Mock
Person person;
@Test
public void testPrintName() throws Exception {
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
Test test= new Test();
test.testMethod();
}
}
Key points to this solution are:
Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)
Instruct Powermock to prepare Test.class
for manipulation of private fields: @PrepareForTest({ Test.class })
And finally mock the constructor for Person class:
PowerMockito.mockStatic(Person.class);
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
Install Fake GPS app https://play.google.com/store/apps/details?id=com.incorporateapps.fakegps.fre&hl=en
Developer options -> Select mock location app(It's mean, Fake location app selected).
Fake GPS app:
Double tab on the map to add -> click the play button -> Show the toast "Fake location stopped"
finally check with google map apps.
The answer by @hybrid is quite informative, except it doesn't explain the purpose as mentioned by @ashitaka "What if you use the Mobile First approach? So, we have the mobile CSS first and then use min-width to target larger sites. We shouldn't use the only keyword in that context, right? "
Want to add in here that the purpose is simply to prevent non supporting browsers to use that Other device style as if it starts from "screen" without it will take it for a screen whereas if it starts from "only" style will be ignored.
Answering to ashitaka consider this example
<link rel="stylesheet" type="text/css"
href="android.css" media="only screen and (max-width: 480px)" />
<link rel="stylesheet" type="text/css"
href="desktop.css" media="screen and (min-width: 481px)" />
If we don't use "only" it will still work as desktop-style will also be used striking android styles but with unnecessary overhead. In this case, IF a browser is non-supporting it will fallback to the second Style-sheet ignoring the first.
You need the secret string which was used to generate encrypt token. This code works for me:
protected string GetName(string token)
{
string secret = "this is a string used for encrypt and decrypt token";
var key = Encoding.ASCII.GetBytes(secret);
var handler = new JwtSecurityTokenHandler();
var validations = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
var claims = handler.ValidateToken(token, validations, out var tokenSecure);
return claims.Identity.Name;
}
For Swift 3, many Foundation
types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString
.
The "star sign" is only meaningful if there is something in front of it. If there isn't the tool (grep in this case) may just treat it as an error. For example:
'*xyz' is meaningless
'a*xyz' means zero or more occurrences of 'a' followed by xyz
Follow following steps:
- Copy hello.ko to /lib/modules/'uname-r'/misc/
- Add misc/hello.ko entry in /lib/modules/'uname-r'/modules.dep
- sudo depmod
- sudo modprobe hello
modprobe will check modules.dep file for any dependency.
pull vs fetch:
The way I understand this, is that git pull
is simply a git fetch
followed by git merge
. I.e. you fetch the changes from a remote branch and then merge it into the current branch.
merge vs rebase:
A merge will do as the command says; merge the differences between current branch and the specified branch (into the current branch). I.e. the command git merge another_branch
will the merge another_branch
into the current branch.
A rebase works a bit differently and is kind of cool. Let's say you perform the command git rebase another_branch
. Git will first find the latest common version between the current branch and another_branch
. I.e. the point before the branches diverged. Then git will move this divergent point to the head of the another_branch
. Finally, all the commits in the current branch since the original divergent point are replayed from the new divergent point. This creates a very clean history, with fewer branches and merges.
However, it is not without pitfalls! Since the version history is "rewritten", you should only do this if the commits only exists in your local git repo. That is: Never do this if you have pushed the commits to a remote repo.
The explanation on rebasing given in this online book is quite good, with easy-to-understand illustrations.
pull with rebasing instead of merge
I'm actually using rebase quite a lot, but usually it is in combination with pull:
git pull --rebase
will fetch remote changes and then rebase instead of merge. I.e. it will replay all your local commits from the last time you performed a pull. I find this much cleaner than doing a normal pull with merging, which will create an extra commit with the merges.
The short answer: no.
The long answer:
Fixed formats work better for HTML emails. In my experience you're best off pretending it's 1999 when it comes to HTML emails. Be explicit and use HTML attributes (width="650") where ever possible in your table definitions, not CSS (style="width:650px"). Use fixed widths, no percentages. A table width of 650 pixels wide is a safe bet. Use inline CSS to set text properties.
It's not a matter of what works in "HTML emails", but rather the plethora of email clients and their limited (and sometimes deliberately so in the case of Gmail, Hotmail etc) ability to render HTML.
The following code creates a table with 2 column as a primary key in SQLite.
SOLUTION:
CREATE TABLE IF NOT EXISTS users (
id TEXT NOT NULL,
name TEXT NOT NULL,
pet_name TEXT,
PRIMARY KEY (id, name)
)
If you're not using the less version, here is the line you need to change:
@media (max-width: 767px) { /* Change this to 0 */
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
box-shadow: none;
}
.navbar-nav .open .dropdown-menu > li > a,
.navbar-nav .open .dropdown-menu .dropdown-header {
padding: 5px 15px 5px 25px;
}
.navbar-nav .open .dropdown-menu > li > a {
line-height: 20px;
}
.navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-nav .open .dropdown-menu > li > a:focus {
background-image: none;
}
}
from superuser accepted answer:
sudo mysql -u root
use mysql;
update user set plugin='' where User='root';
flush privileges;
exit;
Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp' Make three hidden text boxes and a button that is click automatically(using javascript). //Code to written in 'show.jsp'
<body>
<form action="display.jsp" method="post">
<input type="hidden" name="u1" value="<%=u1%>"/>
<input type="hidden" name="u2" value="<%=u2%>" />
<input type="hidden" name="u3" value="<%=u3%>" />
<button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
<script type="text/javascript">
document.getElementById("qq").click();
</script>
</body>
// Code to be written in 'display.jsp'
<% String u1 = request.getParameter("u1").toString();
String u2 = request.getParameter("u2").toString();
String u3 = request.getParameter("u3").toString();
%>
If you want to use these variables of servlets in javascript then simply write
<script type="text/javascript">
var a=<%=u1%>;
</script>
Hope it helps :)
Problem:
Try running below(without solution) from Internet Explorer and see the result.
console.log("abcde".includes("cd"));
_x000D_
Solution:
Now run below solution and check the result
if (!String.prototype.includes) {//To check browser supports or not_x000D_
String.prototype.includes = function (str) {//If not supported, then define the method_x000D_
return this.indexOf(str) !== -1;_x000D_
}_x000D_
}_x000D_
console.log("abcde".includes("cd"));
_x000D_
select p.post_title,m.meta_value sale_price ,n.meta_value regular_price
from wp_postmeta m
inner join wp_postmeta n
on m.post_id = n.post_id
inner join wp_posts p
ON m.post_id=p.id
and m.meta_key = '_sale_price'
and n.meta_key = '_regular_price'
AND p.post_type = 'product';
update wp_postmeta m
inner join wp_postmeta n
on m.post_id = n.post_id
inner join wp_posts p
ON m.post_id=p.id
and m.meta_key = '_sale_price'
and n.meta_key = '_regular_price'
AND p.post_type = 'product'
set m.meta_value = n.meta_value;
Please DO NOT use your own custom scheme like that!!! URI schemes are a network global namespace. Do you own the "anton:" scheme world-wide? No? Then DON'T use it.
One option is to have a web site, and have an intent-filter for a particular URI on that web site. For example, this is what Market does to intercept URIs on its web site:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" android:host="market.android.com"
android:path="/search" />
</intent-filter>
Alternatively, there is the "intent:" scheme. This allows you to describe nearly any Intent as a URI, which the browser will try to launch when clicked. To build such a scheme, the best way is to just write the code to construct the Intent you want launched, and then print the result of intent.toUri(Intent.URI_INTENT_SCHEME).
You can use an action with this intent for to find any activity supporting that action. The browser will automatically add the BROWSABLE category to the intent before launching it, for security reasons; it also will strip any explicit component you have supplied for the same reason.
The best way to use this, if you want to ensure it launches only your app, is with your own scoped action and using Intent.setPackage() to say the Intent will only match your app package.
Trade-offs between the two:
http URIs require you have a domain you own. The user will always get the option to show the URI in the browser. It has very nice fall-back properties where if your app is not installed, they will simply land on your web site.
intent URIs require that your app already be installed and only on Android phones. The allow nearly any intent (but always have the BROWSABLE category included and not supporting explicit components). They allow you to direct the launch to only your app without the user having the option of instead going to the browser or any other app.
overflow-x: auto;
overflow-y : hidden;
Apply the styling above to the parent div.
Thank you very much for the replies!
Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:
1 39.00 9.00
You'll end up with:
1 78.00 48.00
Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.
After much struggling, I think that the following query returns what I need it to:
SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
SELECT invoiceid, SUM(p.amount) amount
FROM invoicepayments ip
LEFT JOIN payments p ON ip.paymentid = p.paymentid
GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'
Would you guys concur?
I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).
e.g. (from the doc)
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
C++ allows static const members to be defined inside a class
Nope, 3.1 §2 says:
A declaration is a definition unless it declares a function without specifying the function's body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification (7.5) and neither an initializer nor a functionbody, it declares a static data member in a class definition (9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), or it is a typedef declaration (7.1.3), a using-declaration (7.3.3), or a using-directive (7.3.4).
I finally understood the problem:
methodA() {
methodB()
}
@Transactional(noRollbackFor = Exception.class)
methodB() {
...
try {
methodC()
} catch (...) {...}
log("OK");
}
@Transactional
methodC() {
throw new ...();
}
What happens is that even though the methodB
has the right annotation, the methodC
does not. When the exception is thrown, the second @Transactional
marks the first transaction as Rollback only anyway.
This is an old question, but I'd say none of the answers really fits the OP's question. All he wanted/needed to do is this:
char c = std::fgetc(fp);
std::strcpy(buffer, &c);
The relevant aspect here is the fact, that the second argument of strcpy()
doesn't need to be a char array / c-string. In fact, none of the arguments is a char or char array at all. They are both char pointers:
strcpy(char* dest, const char* src);
dest :
A non-const char pointersrc :
A const char pointer\0
within its remaining elements (starting with src
), to mark the end of the c-string that should be copied.Another way I just found!
MOVE the project to some other folder and then import and if required copy to workspace
You can hide an image using javascript like this:
document.images['imageName'].style.visibility = hidden;
If that isn't what you are after, you need to explain yourself more clearly.
Write your event handler declaration like this:
<a href="#" onclick="myFunc(event,1,2,3)">click</a>
Then your "myFunc()" function can access the event.
The string value of the "onclick" attribute is converted to a function in a way that's almost exactly the same as the browser (internally) calling the Function constructor:
theAnchor.onclick = new Function("event", theOnclickString);
(except in IE). However, because "event" is a global in IE (it's a window attribute), you'll be able to pass it to the function that way in any browser.
in java you can inherit from one (abstract) class to "provide" functionality and you can implement many interfaces to "ensure" functionality
pkill <process id>
userdel <username>
If it's conciseness you're after, you might like:
prop.table(table(tips$smoker))
and then scale by 100 and round if you like. Or more like your exact output:
tbl <- table(tips$smoker)
cbind(tbl,prop.table(tbl))
If you wanted to do this for multiple columns, there are lots of different directions you could go depending on what your tastes tell you is clean looking output, but here's one option:
tblFun <- function(x){
tbl <- table(x)
res <- cbind(tbl,round(prop.table(tbl)*100,2))
colnames(res) <- c('Count','Percentage')
res
}
do.call(rbind,lapply(tips[3:6],tblFun))
Count Percentage
Female 87 35.66
Male 157 64.34
No 151 61.89
Yes 93 38.11
Fri 19 7.79
Sat 87 35.66
Sun 76 31.15
Thur 62 25.41
Dinner 176 72.13
Lunch 68 27.87
If you don't like stack the different tables on top of each other, you can ditch the do.call
and leave them in a list.
To list remote branches:
git branch -r
You can check them out as local branches with:
git checkout -b LocalName origin/remotebranchname
To get only own methods, and exclude inherited ones:
From within the instance:
self.methods - self.class.superclass.instance_methods
From outside:
TestClass.instance_methods - TestClass.superclass.instance_methods
Add it to the class:
class TestClass
class << self
def own_methods
self.instance_methods - self.superclass.instance_methods
end
end
end
TestClass.own_methods
=> [:method1, :method2, :method3]
(with ruby 2.6.x)
It's confusing because Git logs may suggest any connection or ssh authorization errors, eg: ssh_dispatch_run_fatal: Connection to x.x.x.x port yy: message authentication code incorrect
, the remote end hung up unexpectedly
, early EOF
.
Server-side solution
Let's optimize git repository on the server side:
git gc
.git repack -A
Eg:
ssh admin@my_server_url.com
sudo su git
cd /home/git/my_repo_name # where my server's bare repository exists.
git gc
git repack -A
Now I am able clone this repository without errors, e.g. on the client side:
git clone git@my_server_url.com:my_repo_name
The command git gc
may be called at the git client side to avoid similar git push
problem.
If you are an administrator of Gitlab service - trigger Housekeeping manually. It calls internally git gc
or git repack
.
Client-side solution
Other (hack, client-side only) solution is downloading last master without history:
git clone --single-branch --depth=1 git@my_server_url.com:my_repo_name
There is a chance that buffer overflow will not occur.
You just CAST()
this way
SELECT cast(yourNumber as varchar(10))
FROM yourTable
Then if you want to JOIN
based on it, you can use:
SELECT *
FROM yourTable t1
INNER JOIN yourOtherTable t2
on cast(t1.yourNumber as varchar(10)) = t2.yourString
for a do - while loop containing try statements
loop = True
while loop:
generic_stuff()
try:
questionable_stuff()
# to break from successful completion
# loop = False
except:
optional_stuff()
# to break from unsuccessful completion -
# the case referenced in the OP's question
loop = False
finally:
more_generic_stuff()
alternatively, when there's no need for the 'finally' clause
while True:
generic_stuff()
try:
questionable_stuff()
# to break from successful completion
# break
except:
optional_stuff()
# to break from unsuccessful completion -
# the case referenced in the OP's question
break
If you use a connection script, dont forget to use session_start();
at the connection too, had some trouble before noticing that issue.
First initialize webservices:
$client = new SoapClient("http://example.com/webservices?wsdl");
Then set and pass the parameters:
$params = array (
"arg0" => $contactid,
"arg1" => $desc,
"arg2" => $contactname
);
$response = $client->__soapCall('methodname', array($params));
Note that the method name is available in WSDL as operation name, e.g.:
<operation name="methodname">
To summarize and complement the existing answers, as of Windows PowerShell v5.1 / PowerShell Core 7.0.0-preview.4:
David Mohundro's answer rightfully points that instead of [bool]
parameters you should use [switch]
parameters in PowerShell, where the presence vs. absence of the switch name (-Unify
specified vs. not specified) implies its value, which makes the original problem go away.
However, on occasion you may still need to pass the switch value explicitly, particularly if you're constructing a command line programmatically:
In PowerShell Core, the original problem (described in Emperor XLII's answer) has been fixed.
That is, to pass $true
explicitly to a [switch]
parameter named -Unify
you can now write:
pwsh -File .\RunScript.ps1 -Unify:$true # !! ":" separates name and value, no space
The following values can be used: $false
, false
, $true
, true
, but note that passing 0
or 1
does not work.
Note how the switch name is separated from the value with :
and there must be no whitespace between the two.
Note: If you declare a [bool]
parameter instead of a [switch]
(which you generally shouldn't), you must use the same syntax; even though -Unify $false
should work, it currently doesn't - see this GitHub issue.
In Windows PowerShell, the original problem persists, and - given that Windows PowerShell is no longer actively developed - is unlikely to get fixed.
The workaround suggested in LarsWA's answer - even though it is based on the official help topic as of this writing - does not work in v5.1
Using -Command
instead of -File
is the only effective workaround:
:: # From cmd.exe
powershell -Command "& .\RunScript.ps1 -Unify:$true"
With -Command
you're effectively passing a piece of PowerShell code, which is then evaluated as usual - and inside PowerShell passing $true
and $false
works (but not true
and false
, as now also accepted with -File
).
Caveats:
Using -Command
can result in additional interpretation of your arguments, such as if they contain $
chars. (with -File
, arguments are literals).
Using -Command
can result in a different exit code.
For details, see this answer and this answer.
For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.
If you want both attachment and text try this based on the accepted answer :
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "yourHost");
props.put("mail.smtp.port", "yourHostPort");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailFrom));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
msg.setSubject("your subject");
Multipart multipart = new MimeMultipart();
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText("your text");
MimeBodyPart attachmentBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"
multipart.addBodyPart(textBodyPart); // add the text part
multipart.addBodyPart(attachmentBodyPart); // add the attachement part
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
LOGGER.log(Level.SEVERE,"Error while sending email",e);
}
Update :
If you want to send a mail as an html content formated you have to do
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(content, "text/html");
So basically setText
is for raw text and will be well display on every server email including gmail, setContent
is more for an html template and if you content is formatted as html it will maybe also works in gmail
If you want to apply the style even after getting struck-trough indication, you can use "!important"
to enforce the style. It may not be a right solution but solve the problem.
As Get-Date
returns a DateTime object you are able to compare them directly. An example:
(get-date 2010-01-02) -lt (get-date 2010-01-01)
will return false.
If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.
You should add the resources in a library project as per http://developer.android.com/tools/support-library/setup.html
Section > Adding libraries with resources
You then add the android-support-v7-appcompat
library in your workspace and then add it as a reference to your app project.
Defining all the resources in your app project will also work (but there are a lot of definitions to add and you have missed some of them), and it is not the recommended approach.
Check that you don't have a .my.cnf hiding in your homedir. That was my problem.
You're not parsing a string, you're parsing an already-parsed object :)
var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
// ^ ^
// if you want to parse, the input should be a string
var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.
UPDATE TX_Master_PCBA
SET TIMESTAMP2 = '2013-12-12 15:40:31.593',
G_FIELD='0000'
WHERE TIMESTAMP2 IN
(
SELECT TOP 1 TIMESTAMP2
FROM TX_Master_PCBA WHERE SERIAL_NO='0500030309'
ORDER BY TIMESTAMP2 DESC -- You need to decide what column you want to sort on
)
i have some problems with it, and fixed it my using another config variable
$cfg['Servers'][$i]['AllowNoPassword'] = true;
instead
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;
may be it will helpfull ot someone
I managed to stop this by carrying out the following steps.
cd "C:\Program Files\Git\mingw64\libexec\git-core"
followed by git-credential-manager.exe uninstall
git config --global credential.helper wincred
NOTE: I was using a Personal Access Token as my password.
This works for me, and in this case was a remote connection: Note: The port was IMPORTANT for me
$dsn = "sqlsrv:Server=server.dyndns.biz,1433;Database=DBNAME";
$conn = new PDO($dsn, "root", "P4sw0rd");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM Table";
foreach ($conn->query($sql) as $row) {
print_r($row);
}
For Mysql please see the LOAD XML
SyntaxDocs.
It should work without any additional XML transformation for the XML you've provided, just specify the format and define the table inside the database firsthand with matching column names:
LOAD XML LOCAL INFILE 'table1.xml'
INTO TABLE table1
ROWS IDENTIFIED BY '<table1>';
There is also a related question:
For Postgresql I do not know.
I use XCOPY
with the following parameters for copying .NET assemblies:
/D /Y /R /H
/D:m-d-y - Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time.
/Y - Suppresses prompting to confirm you want to overwrite an existing destination file.
/R - Overwrites read-only files.
/H - Copies hidden and system files also.
Just run your console and type:
db.version()
https://docs.mongodb.com/manual/reference/method/db.version/
Wget 1.18 may work better, e.g., I got bitten by a version 1.12 bug where...
wget --recursive (...)
...only retrieves index.html instead of all files.
Workaround was to notice some 301 redirects and try the new location — given the new URL, wget got all the files in the directory.
If you're OK with littering your markup a bit, you could do it the easy way and just wrap your <button>
with an anchor (<a>
) link.
<a href="#/new-page.html"><button>New Page<button></a>
Also, there is nothing stopping you from styling an anchor link to look like a <button>
as pointed out in the comments by @tronman, this is not technically valid html5, but it should not cause any problems in practice
..... Toast t = Toast.makeText(context, "try... " , Toast.LENGTH_SHORT); t.show();
Cursor callInitCheck = db.rawQuery("select count(*) from call", null);
Toast t2a = Toast.makeText(context, "count rows " + callInitCheck.getCount() , Toast.LENGTH_SHORT);
t2a.show();
callInitCheck.moveToNext();
if( Integer.parseInt( callInitCheck.getString(0)) == 0) // if no rows then do
{
// if empty then insert into call
.....
Why don't we just apply the definition studied at College? The result maybe inefficient but clear, as the multiplication is just a recursive subtraction and subtraction is an addition, then the addition can be performed by a recursive xor/and logic port combination.
#include <stdio.h>
int add(int a, int b){
int rc;
int carry;
rc = a ^ b;
carry = (a & b) << 1;
if (rc & carry)
return add(rc, carry);
else
return rc ^ carry;
}
int sub(int a, int b){
return add(a, add(~b, 1));
}
int div( int D, int Q )
{
/* lets do only positive and then
* add the sign at the end
* inversion needs to be performed only for +Q/-D or -Q/+D
*/
int result=0;
int sign=0;
if( D < 0 ) {
D=sub(0,D);
if( Q<0 )
Q=sub(0,Q);
else
sign=1;
} else {
if( Q<0 ) {
Q=sub(0,Q);
sign=1;
}
}
while(D>=Q) {
D = sub( D, Q );
result++;
}
/*
* Apply sign
*/
if( sign )
result = sub(0,result);
return result;
}
int main( int argc, char ** argv )
{
printf( "2 plus 3=%d\n", add(2,3) );
printf( "22 div 3=%d\n", div(22,3) );
printf( "-22 div 3=%d\n", div(-22,3) );
printf( "-22 div -3=%d\n", div(-22,-3) );
printf( "22 div 03=%d\n", div(22,-3) );
return 0;
}
As someone says... first make this work. Note that algorithm should work for negative Q...
public class UserInfo {
String LoginId;
String Password;
String FirstName;
String LastName;
String Email;
String Mobile;
String Address;
String DOB;
public String getLoginId() {
return LoginId;
}
public void setLoginId(String loginId) {
LoginId = loginId;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getMobile() {
return Mobile;
}
public void setMobile(String mobile) {
Mobile = mobile;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getDOB() {
return DOB;
}
public void setDOB(String DOB) {
this.DOB = DOB;
}
}
Use the .data()
method:
$('div').data('info', '222');
Note that this doesn't create an actual data-info
attribute. If you need to create the attribute, use .attr()
:
$('div').attr('data-info', '222');
The array will be initialized to false when you allocate it.
All arrays in Java are initialized to the default value for the type. This means that arrays of ints are initialised to 0, arrays of booleans are initialised to false and arrays of reference types are initialised to null.
Sorry for the late answer.. For mac users command + option + o Try this.. It is working for me..
If you or some other fox who need to have link with Icon Image and text as link text beside the image see bellow code:
CSS
.linkWithImageIcon{
Display:inline-block;
}
.MyLink{
Background:#FF3300;
width:200px;
height:70px;
vertical-align:top;
display:inline-block; font-weight:bold;
}
.MyLinkText{
/*---The margin depends on how the image size is ---*/
display:inline-block; margin-top:5px;
}
HTML
<a href="#" class="MyLink"><img src="./yourImageIcon.png" /><span class="MyLinkText">SIGN IN</span></a>
if you see the image the white portion is image icon and other is style this way you can create different buttons with any type of Icons you want to design
Think this way:
Spring MVC is a web based framework to implement the MVC architecture.
Spring Boot is a tool oriented to the programmer. Programmer must focus on programming and tool must focus on configurations. So we don't need to wast our time configuring a bunch of xml to make a simple 'Hello world'.
from tkinter import *
from PIL import ImageTk, Image
window = Tk()
window.geometry("1000x300")
path = "1.jpg"
image = PhotoImage(Image.open(path))
panel = Label(window, image = image)
panel.pack()
window.mainloop()
The outfile should be in binary mode.
outFile = open('output.xml', 'wb')
Easiest is to use strftime
(docs).
If it's for use on the view side, better to wrap it in a helper, though.
Personally, I do the following:
session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();
That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy
).
remember, SSL/TLS operates at the Transport Layer, so all the crypto goo happens under the application-layer HTTP stuff.
http://en.wikipedia.org/wiki/File:IP_stack_connections.svg
that's the long way of saying, "Yes!"
You want to use Test-Path
:
Test-Path <path to file> -PathType Leaf
I don't think you need the trailing slash in the URL entry. Ie, put this instead:
(r'^led-tv$', filter_by_led ),
This is assuming you have trailing slashes enabled, which is the default.
If you have jQuery defined twice, then you could get this error. For example, if you are working with Primefaces (it already includes jQuery) and you define it in other place.
Yes; copy the string to a char array, sort the char array, then copy that back into a string.
static string SortString(string input)
{
char[] characters = input.ToArray();
Array.Sort(characters);
return new string(characters);
}
During the download of wamp server from wampserver website you get a warning..
WARNING : Vous devez avoir installé Visual Studio 2012 : VC 11 vcredist_x64/86.exe Visual Studio 2012 VC 11 vcredist_x64/86.exe : http://www.microsoft.com/en-us/download/details.aspx?id=30679
So if you install the vcredist_xxx.exe it will be ok
For those who switched to Kotlin just use
string.toLong()
That will call Long.parseLong(string)
under the hood
Using pstools - in particular psservice and "query" - for example:
psservice query "serviceName"
Note that on Python 3, it's not really fair to say any of:
str
s are UTFx for any x (eg. UTF8)
str
s are Unicode
str
s are ordered collections of Unicode characters
Python's str
type is (normally) a sequence of Unicode code points, some of which map to characters.
Even on Python 3, it's not as simple to answer this question as you might imagine.
An obvious way to test for ASCII-compatible strings is by an attempted encode:
"Hello there!".encode("ascii")
#>>> b'Hello there!'
"Hello there... ?!".encode("ascii")
#>>> Traceback (most recent call last):
#>>> File "", line 4, in <module>
#>>> UnicodeEncodeError: 'ascii' codec can't encode character '\u2603' in position 15: ordinal not in range(128)
The error distinguishes the cases.
In Python 3, there are even some strings that contain invalid Unicode code points:
"Hello there!".encode("utf8")
#>>> b'Hello there!'
"\udcc3".encode("utf8")
#>>> Traceback (most recent call last):
#>>> File "", line 19, in <module>
#>>> UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc3' in position 0: surrogates not allowed
The same method to distinguish them is used.
None of the solutions worked for me. For those who are still on PHP 5.2 (DateTime::diff was introduced in 5.3), this solution works:
function howDays($from, $to) {
$first_date = strtotime($from);
$second_date = strtotime($to);
$offset = $second_date-$first_date;
return floor($offset/60/60/24);
}
I would recommend creating a function like this:
function isEmptyEl(array, i) {
return !(array[i]);
}
You could call it like this:
if (isEmptyEl(arrayName, indexVal)) {
console.log('arrayName[' + indexVal + '] is empty');
}
Forcing the developer to adhere to the isEmptyEl interface will catch input errors such as an undefined arrayName or indexVal variables.
(It's generally good practice to program defensively when programming in Javascript.)
You would get an error thrown like this if arrayName was not defined:
Uncaught ReferenceError: arrayName is not defined
at <anonymous>:2:15
at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
at Object.InjectedScript.evaluate (<anonymous>:694:21)
Similar results for an undefined indexVal.
You get an error if the array or index values do not exist.
For valid input, you'll only get a true if arrayName[indexVal] is any of the following:
No, you can't instantite an abstract class.We instantiate only anonymous class.In abstract class we declare abstract methods and define concrete methods only.
There are some open source alternatives:
Create table abc select * from def limit 0;
This will definite work
Just use:
param.AddWithValue("@Date_Of_Birth",DOB);
That will take care of all your problems.
In Sender Activity Side:
Intent passIntent = new Intent(getApplicationContext(), "ActivityName".class);
passIntent.putExtra("value", integerValue);
startActivity(passIntent);
In Receiver Activity Side:
int receiveValue = getIntent().getIntExtra("value", 0);
I agree with @maverik above, I prefer not to hide the details with a typedef. Especially when you are trying to understand what is going on. I also prefer to see everything instead of a partial code snippet. With that said, here is a malloc and free of a complex structure.
The code uses the ms visual studio leak detector so you can experiment with the potential leaks.
#include "stdafx.h"
#include <string.h>
#include "msc-lzw.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
// 32-bit version
int hash_fun(unsigned int key, int try_num, int max) {
return (key + try_num) % max; // the hash fun returns a number bounded by the number of slots.
}
// this hash table has
// key is int
// value is char buffer
struct key_value_pair {
int key; // use this field as the key
char *pValue; // use this field to store a variable length string
};
struct hash_table {
int max;
int number_of_elements;
struct key_value_pair **elements; // This is an array of pointers to mystruct objects
};
int hash_insert(struct key_value_pair *data, struct hash_table *hash_table) {
int try_num, hash;
int max_number_of_retries = hash_table->max;
if (hash_table->number_of_elements >= hash_table->max) {
return 0; // FULL
}
for (try_num = 0; try_num < max_number_of_retries; try_num++) {
hash = hash_fun(data->key, try_num, hash_table->max);
if (NULL == hash_table->elements[hash]) { // an unallocated slot
hash_table->elements[hash] = data;
hash_table->number_of_elements++;
return RC_OK;
}
}
return RC_ERROR;
}
// returns the corresponding key value pair struct
// If a value is not found, it returns null
//
// 32-bit version
struct key_value_pair *hash_retrieve(unsigned int key, struct hash_table *hash_table) {
unsigned int try_num, hash;
unsigned int max_number_of_retries = hash_table->max;
for (try_num = 0; try_num < max_number_of_retries; try_num++) {
hash = hash_fun(key, try_num, hash_table->max);
if (hash_table->elements[hash] == 0) {
return NULL; // Nothing found
}
if (hash_table->elements[hash]->key == key) {
return hash_table->elements[hash];
}
}
return NULL;
}
// Returns the number of keys in the dictionary
// The list of keys in the dictionary is returned as a parameter. It will need to be freed afterwards
int keys(struct hash_table *pHashTable, int **ppKeys) {
int num_keys = 0;
*ppKeys = (int *) malloc( pHashTable->number_of_elements * sizeof(int) );
for (int i = 0; i < pHashTable->max; i++) {
if (NULL != pHashTable->elements[i]) {
(*ppKeys)[num_keys] = pHashTable->elements[i]->key;
num_keys++;
}
}
return num_keys;
}
// The dictionary will need to be freed afterwards
int allocate_the_dictionary(struct hash_table *pHashTable) {
// Allocate the hash table slots
pHashTable->elements = (struct key_value_pair **) malloc(pHashTable->max * sizeof(struct key_value_pair)); // allocate max number of key_value_pair entries
for (int i = 0; i < pHashTable->max; i++) {
pHashTable->elements[i] = NULL;
}
// alloc all the slots
//struct key_value_pair *pa_slot;
//for (int i = 0; i < pHashTable->max; i++) {
// // all that he could see was babylon
// pa_slot = (struct key_value_pair *) malloc(sizeof(struct key_value_pair));
// if (NULL == pa_slot) {
// printf("alloc of slot failed\n");
// while (1);
// }
// pHashTable->elements[i] = pa_slot;
// pHashTable->elements[i]->key = 0;
//}
return RC_OK;
}
// This will make a dictionary entry where
// o key is an int
// o value is a character buffer
//
// The buffer in the key_value_pair will need to be freed afterwards
int make_dict_entry(int a_key, char * buffer, struct key_value_pair *pMyStruct) {
// determine the len of the buffer assuming it is a string
int len = strlen(buffer);
// alloc the buffer to hold the string
pMyStruct->pValue = (char *) malloc(len + 1); // add one for the null terminator byte
if (NULL == pMyStruct->pValue) {
printf("Failed to allocate the buffer for the dictionary string value.");
return RC_ERROR;
}
strcpy(pMyStruct->pValue, buffer);
pMyStruct->key = a_key;
return RC_OK;
}
// Assumes the hash table has already been allocated.
int add_key_val_pair_to_dict(struct hash_table *pHashTable, int key, char *pBuff) {
int rc;
struct key_value_pair *pKeyValuePair;
if (NULL == pHashTable) {
printf("Hash table is null.\n");
return RC_ERROR;
}
// Allocate the dictionary key value pair struct
pKeyValuePair = (struct key_value_pair *) malloc(sizeof(struct key_value_pair));
if (NULL == pKeyValuePair) {
printf("Failed to allocate key value pair struct.\n");
return RC_ERROR;
}
rc = make_dict_entry(key, pBuff, pKeyValuePair); // a_hash_table[1221] = "abba"
if (RC_ERROR == rc) {
printf("Failed to add buff to key value pair struct.\n");
return RC_ERROR;
}
rc = hash_insert(pKeyValuePair, pHashTable);
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
return RC_OK;
}
void dump_hash_table(struct hash_table *pHashTable) {
// Iterate the dictionary by keys
char * pValue;
struct key_value_pair *pMyStruct;
int *pKeyList;
int num_keys;
printf("i\tKey\tValue\n");
printf("-----------------------------\n");
num_keys = keys(pHashTable, &pKeyList);
for (int i = 0; i < num_keys; i++) {
pMyStruct = hash_retrieve(pKeyList[i], pHashTable);
pValue = pMyStruct->pValue;
printf("%d\t%d\t%s\n", i, pKeyList[i], pValue);
}
// Free the key list
free(pKeyList);
}
int main(int argc, char *argv[]) {
int rc;
int i;
struct hash_table a_hash_table;
a_hash_table.max = 20; // The dictionary can hold at most 20 entries.
a_hash_table.number_of_elements = 0; // The intial dictionary has 0 entries.
allocate_the_dictionary(&a_hash_table);
rc = add_key_val_pair_to_dict(&a_hash_table, 1221, "abba");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
rc = add_key_val_pair_to_dict(&a_hash_table, 2211, "bbaa");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
rc = add_key_val_pair_to_dict(&a_hash_table, 1122, "aabb");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
rc = add_key_val_pair_to_dict(&a_hash_table, 2112, "baab");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
rc = add_key_val_pair_to_dict(&a_hash_table, 1212, "abab");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
rc = add_key_val_pair_to_dict(&a_hash_table, 2121, "baba");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
// Iterate the dictionary by keys
dump_hash_table(&a_hash_table);
// Free the individual slots
for (i = 0; i < a_hash_table.max; i++) {
// all that he could see was babylon
if (NULL != a_hash_table.elements[i]) {
free(a_hash_table.elements[i]->pValue); // free the buffer in the struct
free(a_hash_table.elements[i]); // free the key_value_pair entry
a_hash_table.elements[i] = NULL;
}
}
// Free the overall dictionary
free(a_hash_table.elements);
_CrtDumpMemoryLeaks();
return 0;
}
I had same problem on Visual Studio C++ 2010. It's easy to fix. Above the main() function just replace the standard include lines with this below but with the pound symbol in front of the includes.
# include "stdafx.h"
# include <iostream>
using namespace std;
As per bash - The Set Builtin manual, if -e
/errexit
is set, the shell exits immediately if a pipeline consisting of a single simple command, a list or a compound command returns a non-zero status.
By default, the exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail
option is enabled (it's disabled by default).
If so, the pipeline's return status of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.
If you'd like to execute something on exit, try defining trap
, for example:
trap onexit EXIT
where onexit
is your function to do something on exit, like below which is printing the simple stack trace:
onexit(){ while caller $((n++)); do :; done; }
There is similar option -E
/errtrace
which would trap on ERR instead, e.g.:
trap onerr ERR
Zero status example:
$ true; echo $?
0
Non-zero status example:
$ false; echo $?
1
Negating status examples:
$ ! false; echo $?
0
$ false || true; echo $?
0
Test with pipefail
being disabled:
$ bash -c 'set +o pipefail -e; true | true | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; false | false | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; true | true | false; echo success'; echo $?
1
Test with pipefail
being enabled:
$ bash -c 'set -o pipefail -e; true | false | true; echo success'; echo $?
1
This is a late answer but I am putting it here for posterity
You can edit the svg and set its size. one of the reasons I like using svg's is because you can edit it in a text editor.
The following is a 32*32 svg which I internally resized to initially display as a 10*10 image. it worked perfectly to replace the list image
<?xml version="1.0" ?><svg width="10" height="10" id="chevron-right" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg"><path style="fill:#34a89b;" d="M12 1 L26 16 L12 31 L8 27 L18 16 L8 5 z"/></svg>
I then simply added the following to my css
* ul {
list-style: none;
list-style-image: url(../images/chevron-right.svg);
}
The list-style: none;
is important as it prevents the default list image from displaying while the alternate image is being loaded.
I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path
to get a relative file path:
Sub SaveToRelativePath()
Dim relativePath As String
relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.
The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.
The shortest code
ChromeDriver drv = new ChromeDriver();
drv.Navigate().GoToUrl("https://stackoverflow.com/questions/6229769/execute-javascript-using-selenium-webdriver-in-c-sharp");
drv.ExecuteScript("return alert(document.title);");
My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it's not what you wanted, but I already wrote this answer before I realized that. So, I'm going to post it in case other people (or even you) find it useful.
You just need nested loops with an input statement at each loop's level.
For instance,
data=""
while 1:
data=raw_input("Command: ")
if data in ("test", "experiment", "try"):
data2=""
while data2=="":
data2=raw_input("Which test? ")
if data2=="chemical":
print("You chose a chemical test.")
else:
print("We don't have any " + data2 + " tests.")
elif data=="quit":
break
else:
pass
I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.
In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.
The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told
<body>
<a id=id_page href ="#loving" onclick="load_services()"> loving </a>
<script>
// This script MUST BE under the "ID" that is calling
// Do not transfer it to a differ DIV than the caller "ID"
document.getElementById("id_page").addEventListener("click", function(){
document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
</script>
</body>
<div id="mainbody" class="main_body">
"here is loaded the external html file when the loving link will
be clicked. "
</div>
the bottom cell will grow as you enter more text ... setting the table width will help too
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>
You can try wiht TIMESTAMP(curdate(), curtime()) for use the current time.
How about using FONT tag?
Like:
H<font color="red">E</font>LLO.
Can't show example here, because this site doesn't allow font tag use.
Span style is fast and easy too.
>>
is arithmetic shift right, >>>
is logical shift right.
In an arithmetic shift, the sign bit is extended to preserve the signedness of the number.
For example: -2 represented in 8 bits would be 11111110
(because the most significant bit has negative weight). Shifting it right one bit using arithmetic shift would give you 11111111
, or -1. Logical right shift, however, does not care that the value could possibly represent a signed number; it simply moves everything to the right and fills in from the left with 0s. Shifting our -2 right one bit using logical shift would give 01111111
.
This works for anonymous types, ExpandoObject
, Nancy.DynamicDictionary
or anything else that can be cast to IDictionary<string, object>
.
public static bool PropertyExists(dynamic obj, string name) {
if (obj == null) return false;
if (obj is IDictionary<string, object> dict) {
return dict.ContainsKey(name);
}
return obj.GetType().GetProperty(name) != null;
}
What works for me on /FF and /Chrome:
body {
position: fixed;
width: 100%;
height: 100%;
}
overflow: hidden
just disables display of the scrollbars. (But you can put it in there if you like to).
There is one drawback I found: If you use this method on a page which you want only temporarily to stop scrolling, setting position: fixed
will scroll it to the top.
This is because position: fixed uses absolute positions which are currently set to 0/0.
This can be repaired e.g. with jQuery:
var lastTop;
function stopScrolling() {
lastTop = $(window).scrollTop();
$('body').addClass( 'noscroll' )
.css( { top: -lastTop } )
;
}
function continueScrolling() {
$('body').removeClass( 'noscroll' );
$(window).scrollTop( lastTop );
}
You can use Dialog to create this easily
create a Dialog instance using the context
Dialog dialog = new Dialog(contex);
You can design your layout as you like.
You can add this layout to your dialog by
dialog.setContentView(R.layout.popupview);//popup view is the layout you created
then you can access its content (textviews, etc.) by using findViewById
method
TextView txt = (TextView)dialog.findViewById(R.id.textbox);
you can add any text here. the text can be stored in the String.xml file in res\values.
txt.setText(getString(R.string.message));
then finally show the pop up menu
dialog.show();
more information http://developer.android.com/guide/topics/ui/dialogs.html
http://developer.android.com/reference/android/app/Dialog.html
I did a test using the Chrome address bar and a $QUERY_STRING
in bash, and observed the following:
~!@$%^&*()-_=+[{]}\|;:',./?
and grave (backtick)
are passed through as plaintext.
,
"
, <
and >
are converted to %20
, %22
, %3C
and %3E
respectively.
#
is ignored, since it is used by ye olde anchor.
Personally, I'd say bite the bullet and encode with base64 :)
Use JQuery, its easy.
Include the JQuery library into your html file in the head as such:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
(Make sure that this script tag goes before your other script tags in your html file)
Target your id in your JavaScript file as such:
<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');
//your var will be the src string that you're looking for
</script>
For me shutil.copy is the best:
import shutil
#make a copy of the invoice to work with
src="invoice.pdf"
dst="copied_invoice.pdf"
shutil.copy(src,dst)
You can change the path of the files as you want.
var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);
CSV can get complicated real fast.
Use something robust and well-tested:
FileHelpers:
www.filehelpers.net
The FileHelpers are a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.
They might be just a \r
or a \n
. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n
.
This string
string test = "blah\r\nblah\rblah\nblah";
Shows up as
blah
blah
blah
blah
in the text visualizer.
So you could try
string modifiedString = originalString
.Replace(Environment.NewLine, "<br />")
.Replace("\r", "<br />")
.Replace("\n", "<br />");
As of Maven Eclipse (m2e) version 0.12 all Maven life-cycle goals must map to an installed m2e extension. In this case, the maven-ear-plugin
had an-unmapped goal default-generate-application-xml
.
You can exclude un-mapped life-cycle goals by simply following the instructions here:
https://wiki.eclipse.org/M2E_plugin_execution_not_covered
Alternatively, simply right-click on the error message in Eclipse and choosing Quick Fix
-> Ignore for every pom with such errors
.
You should be careful when ignoring life-cycle goals: typically goals do something useful and if you configure them to be ignored in Eclipse you may miss important build steps. You might also want to consider adding support to the Maven Eclipse EAR extension for the unmapped life-cycle goal.
Open the PHP file under question, in Notepad++.
Click on Encoding at the top and change from "Encoding in UTF-8 without BOM" to just "Encoding in UTF-8". Save and overwrite the file on your server.
I do this using the TextMaskModule from 'angular2-text-mask'
Mine are split but you can get the idea
Package using NPM NodeJS
"dependencies": {
"angular2-text-mask": "8.0.0",
HTML
<input *ngIf="column?.type =='areaCode'" type="text" [textMask]="{mask: areaCodeMask}" [(ngModel)]="areaCodeModel">
<input *ngIf="column?.type =='phone'" type="text" [textMask]="{mask: phoneMask}" [(ngModel)]="phoneModel">
Inside Component
public areaCodeModel = '';
public areaCodeMask = ['(', /[1-9]/, /\d/, /\d/, ')'];
public phoneModel = '';
public phoneMask = [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
List node process:
$ ps -e|grep node
Kill the process using
$kill -9 XXXX
Here XXXX is the process number
Other answers have already covered profiling to avoid premature optimization and overhead cost in parallel processing. This answer explains the ideal choice of data structures for parallel streaming.
As a rule, performance gains from parallelism are best on streams over
ArrayList
,HashMap
,HashSet
, andConcurrentHashMap
instances; arrays;int
ranges; andlong
ranges. What these data structures have in common is that they can all be accurately and cheaply split into subranges of any desired sizes, which makes it easy to divide work among parallel threads. The abstraction used by the streams library to perform this task is the spliterator , which is returned by thespliterator
method onStream
andIterable
.Another important factor that all of these data structures have in common is that they provide good-to-excellent locality of reference when processed sequentially: sequential element references are stored together in memory. The objects referred to by those references may not be close to one another in memory, which reduces locality-of-reference. Locality-of-reference turns out to be critically important for parallelizing bulk operations: without it, threads spend much of their time idle, waiting for data to be transferred from memory into the processor’s cache. The data structures with the best locality of reference are primitive arrays because the data itself is stored contiguously in memory.
Source: Item #48 Use Caution When Making Streams Parallel, Effective Java 3e by Joshua Bloch
I would suggest in taking a look into JWE using special algorithms which is not present in jwt.io to decrypt
Reference link: https://www.npmjs.com/package/node-webtokens
jwt.generate('PBES2-HS512+A256KW', 'A256GCM', payload, pwd, (error, token) => {
jwt.parse(token).verify(pwd, (error, parsedToken) => {
// other statements
});
});
This answer may be too late or you might have already found out the way, but still, I felt it would be helpful for you and others as well.
A simple example which I have created: https://github.com/hansiemithun/jwe-example
Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:
EXEC TEST()
Share and enjoy.
Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS
view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:
CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
Y IN NUMBER DEFAULT 1)
AS
varX VARCHAR2(32767) := NVL(X, 'P');
varY NUMBER := NVL(Y, 1);
BEGIN
DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;
We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.
On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:
### log just the SQL
log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug
However, the JDBC bind parameters are not being logged.
I’ve answered your question in-depth here: http://mathiasbynens.be/notes/css-escapes
The article also explains how to escape any character in CSS (and JavaScript), and I made a handy tool for this as well. From that page:
If you were to give an element an ID value of
~!@$%^&*()_+-=,./';:"?><[]{}|`#
, the selector would look like this:CSS:
<style> #\~\!\@\$\%\^\&\*\(\)\_\+-\=\,\.\/\'\;\:\"\?\>\<\[\]\\\{\}\|\`\# { background: hotpink; } </style>
JavaScript:
<script> // document.getElementById or similar document.getElementById('~!@$%^&*()_+-=,./\';:"?><[]\\{}|`#'); // document.querySelector or similar $('#\\~\\!\\@\\$\\%\\^\\&\\*\\(\\)\\_\\+-\\=\\,\\.\\/\\\'\\;\\:\\"\\?\\>\\<\\[\\]\\\\\\{\\}\\|\\`\\#'); </script>
No, not all browsers support the sizes
attribute:
Note that some platforms define specific sizes:
manifest.json
if it is present. Plus, Chrome uses the Apple Touch icon for bookmarks.--user
installs in site.USER_SITE
.
For my case, it was /Users/.../Library/Python/2.7/bin
. So I have added that to my PATH (in ~/.bash_profile
file):
export PATH=$PATH:/Users/.../Library/Python/2.7/bin