Combine JS & CSS :
button{
/* 1st state */
}
button:hover{
/* hover state */
}
button:active{
/* click state */
}
button.active{
/* after click state */
}
jQuery('button').click(function(){
jQuery(this).toggleClass('active');
});
jQuery.val() and .text() will never return 'undefined' for an empty selection. It always returns an empty string (i.e. ""). .html() will return null if the element doesn't exist though.You need to do:
if(page_name != '')
For other variables that don't come from something like jQuery.val() you would do this though:
if(typeof page_name != 'undefined')
You just have to use the typeof
operator.
Try to import
java.util.List;
instead of
java.awt.List;
For a more flexible solution, use the splice()
function. It allows you to remove any item in an Array based on Index Value:
var indexToRemove = 0;
var numberToRemove = 1;
arr.splice(indexToRemove, numberToRemove);
Like this http://jsfiddle.net/8ha9e/1/
Add colspan="2"
to the 3rd <th>
and then have 4 <td>
's in your second row.
<table border="1">
<tr>
<th scope="col">Header</th>
<th scope="col">Header</th>
<th scope="col" colspan="2">Header</th>
</tr>
<tr>
<th scope="row"> </th>
<td> </td>
<!-- The following two cells will appear under the same header -->
<td>Col 1</td>
<td>Col 2</td>
</tr>
</table>
For anyone who is searching for a solution about posting to Instagram using AWS lambda and puppeteer (chrome-aws-lambda). Noted that this solution allow you to post 1 photo for each post only. If you are not using lambda, just replace chrome-aws-lambda
with puppeteer
.
For the first launch of lambda, it is normal that will not work because instagram detects “Suspicious login attempt”. Just goto instagram page using your PC and approve it, everything should be fine.
Here's my code, feel free to optimize it:
// instagram.js
const chromium = require('chrome-aws-lambda');
const username = process.env.IG_USERNAME;
const password = process.env.IG_PASSWORD;
module.exports.post = async function(fileToUpload, caption){
const browser = await chromium.puppeteer.launch({
args: [...chromium.args, '--window-size=520,700'],
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: false,
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) FxiOS/7.5b3349 Mobile/14F89 Safari/603.2.4');
await page.goto('https://www.instagram.com/', {waitUntil: 'networkidle2'});
const [buttonLogIn] = await page.$x("//button[contains(., 'Log In')]");
if (buttonLogIn) {
await buttonLogIn.click();
}
await page.waitFor('input[name="username"]');
await page.type('input[name="username"]', username)
await page.type('input[name="password"]', password)
await page.click('form button[type="submit"]');
await page.waitFor(3000);
const [buttonSaveInfo] = await page.$x("//button[contains(., 'Not Now')]");
if (buttonSaveInfo) {
await buttonSaveInfo.click();
}
await page.waitFor(3000);
const [buttonNotificationNotNow] = await page.$x("//button[contains(., 'Not Now')]");
const [buttonNotificationCancel] = await page.$x("//button[contains(., 'Cancel')]");
if (buttonNotificationNotNow) {
await buttonNotificationNotNow.click();
} else if (buttonNotificationCancel) {
await buttonNotificationCancel.click();
}
await page.waitFor('form[enctype="multipart/form-data"]');
const inputUploadHandle = await page.$('form[enctype="multipart/form-data"] input[type=file]');
await page.waitFor(5000);
const [buttonPopUpNotNow] = await page.$x("//button[contains(., 'Not Now')]");
const [buttonPopUpCancel] = await page.$x("//button[contains(., 'Cancel')]");
if (buttonPopUpNotNow) {
await buttonPopUpNotNow.click();
} else if (buttonPopUpCancel) {
await buttonPopUpCancel.click();
}
await page.click('[data-testid="new-post-button"]')
await inputUploadHandle.uploadFile(fileToUpload);
await page.waitFor(3000);
const [buttonNext] = await page.$x("//button[contains(., 'Next')]");
await buttonNext.click();
await page.waitFor(3000);
await page.type('textarea', caption);
const [buttonShare] = await page.$x("//button[contains(., 'Share')]");
await buttonShare.click();
await page.waitFor(3000);
return true;
};
// handler.js
await instagram.post('/tmp/image.png', '#text');
it must be local file path, if it is url, download it to /tmp folder first.
With Dedexer, you can disassemble the .dex
file into dalvik bytecode (.ddx
).
Decompiling towards Java isn't possible as far as I know.
You can read about dalvik bytecode here.
Since scipy
's imread
is deprecated, use imageio.imread
.
pip install imageio
height, width, channels = imageio.imread(filepath).shape
The error message is due to the call not going through the Request
facade.
Change
use Illuminate\Http\Request;
To
use Request;
and it should start working.
In the config/app.php file, you can find a list of the class aliases. There, you will see that the base class Request
has been aliased to the Illuminate\Support\Facades\Request
class. Because of this, to use the Request
facade in a namespaced file, you need to specify to use the base class: use Request;
.
Since this question seems to get some traffic, I wanted to update the answer a little bit since Laravel 5 was officially released.
While the above is still technically correct and will work, the use Illuminate\Http\Request;
statement is included in the new Controller template to help push developers in the direction of using dependency injection versus relying on the Facade.
When injecting the Request object into the constructor (or methods, as available in Laravel 5), it is the Illuminate\Http\Request
object that should be injected, and not the Request
facade.
So, instead of changing the Controller template to work with the Request facade, it is better recommended to work with the given Controller template and move towards using dependency injection (via constructor or methods).
Example via method
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserController extends Controller {
/**
* Store a newly created resource in storage.
*
* @param Illuminate\Http\Request $request
* @return Response
*/
public function store(Request $request) {
$name = $request->input('name');
}
}
Example via constructor
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserController extends Controller {
protected $request;
public function __construct(Request $request) {
$this->request = $request;
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store() {
$name = $this->request->input('name');
}
}
The following codes should give you the fastest speed for big data as long as you have many cores on your computer:
if (!require("pacman")) install.packages("pacman")
pacman::p_load(doParallel, data.table, stringr)
# get the file name
dir() %>% str_subset("\\.csv$") -> fn
# use parallel setting
(cl <- detectCores() %>%
makeCluster()) %>%
registerDoParallel()
# read and bind all files together
system.time({
big_df <- foreach(
i = fn,
.packages = "data.table"
) %dopar%
{
fread(i, colClasses = "character")
} %>%
rbindlist(fill = TRUE)
})
# end of parallel work
stopImplicitCluster(cl)
Updated in 2020/04/16: As I find a new package available for parallel computation, an alternative solution is provided using the following codes.
if (!require("pacman")) install.packages("pacman")
pacman::p_load(future.apply, data.table, stringr)
# get the file name
dir() %>% str_subset("\\.csv$") -> fn
plan(multiprocess)
future_lapply(fn,fread,colClasses = "character") %>%
rbindlist(fill = TRUE) -> res
# res is the merged data.table
OPTIONS tells you things such as "What methods are allowed for this resource".
HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.
I know that it is very late to answer the question, but it may help someone like me who spent lots off time to fetch data using hql
So the thing is you just have to write a query
Query query = session.createQuery("from Employee");
it will give you all the data list but to fetch data from this you have to write this line.
List<Employee> fetchedData = query.list();
As simple as it looks.
I did the css properties shown here as well as monitor ondragstart with the following javascript:
handleDragStart: function (evt) {
if (evt.target.nodeName.match(/^(IMG|DIV|SPAN|A)$/i)) {
evt.preventDefault();
return false;
}
},
For me, it was vertical-align: baseline
vs vertical-align: top
that was causing the top offset.
Try to set vertical-align: top
If your onclick function returns false the default browser behaviour is cancelled. As such:
<a href='http://www.google.com' onclick='return check()'>check</a>
<script type='text/javascript'>
function check()
{
return false;
}
</script>
Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
Besides the already stated answers about using Vector, Vector also has a bunch of methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation.
There's good amount of detail on logging for shell scripts via global varaibles of shell. We can emulate the similar kind of logging in shell script: http://www.cubicrace.com/2016/03/efficient-logging-mechnism-in-shell.html The post has details on introdducing log levels like INFO , DEBUG, ERROR. Tracing details like script entry, script exit, function entry, function exit.
Yes there still is no API for this (2.1). But it seemed like at WWDC a lot of people were already interested in the functionality (including myself) and the recommendation was to go to the below site and create a feature request for this. If there is enough of an interest, they might end up moving the ICal.framework to the public SDK.
You are probably connecting fine but don't have sufficient privileges to run show dbs
.
You don't need to run the db.auth if you pass the auth in the command line:
mongo somewhere.mongolayer.com:10011/my_database -u username -p password
Once you connect are you able to see collections?
> show collections
If so all is well and you just don't have admin privileges to the database and can't run the show dbs
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
As stated in other answers, you can check the mime type by checking the signature of the file in the first bytes of the file.
But what other answers are doing is loading the entire file in memory in order to check the signature, which is very wasteful and could easily freeze your browser if you select a big file by accident or not.
/**_x000D_
* Load the mime type based on the signature of the first bytes of the file_x000D_
* @param {File} file A instance of File_x000D_
* @param {Function} callback Callback with the result_x000D_
* @author Victor www.vitim.us_x000D_
* @date 2017-03-23_x000D_
*/_x000D_
function loadMime(file, callback) {_x000D_
_x000D_
//List of known mimes_x000D_
var mimes = [_x000D_
{_x000D_
mime: 'image/jpeg',_x000D_
pattern: [0xFF, 0xD8, 0xFF],_x000D_
mask: [0xFF, 0xFF, 0xFF],_x000D_
},_x000D_
{_x000D_
mime: 'image/png',_x000D_
pattern: [0x89, 0x50, 0x4E, 0x47],_x000D_
mask: [0xFF, 0xFF, 0xFF, 0xFF],_x000D_
}_x000D_
// you can expand this list @see https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern_x000D_
];_x000D_
_x000D_
function check(bytes, mime) {_x000D_
for (var i = 0, l = mime.mask.length; i < l; ++i) {_x000D_
if ((bytes[i] & mime.mask[i]) - mime.pattern[i] !== 0) {_x000D_
return false;_x000D_
}_x000D_
}_x000D_
return true;_x000D_
}_x000D_
_x000D_
var blob = file.slice(0, 4); //read the first 4 bytes of the file_x000D_
_x000D_
var reader = new FileReader();_x000D_
reader.onloadend = function(e) {_x000D_
if (e.target.readyState === FileReader.DONE) {_x000D_
var bytes = new Uint8Array(e.target.result);_x000D_
_x000D_
for (var i=0, l = mimes.length; i<l; ++i) {_x000D_
if (check(bytes, mimes[i])) return callback("Mime: " + mimes[i].mime + " <br> Browser:" + file.type);_x000D_
}_x000D_
_x000D_
return callback("Mime: unknown <br> Browser:" + file.type);_x000D_
}_x000D_
};_x000D_
reader.readAsArrayBuffer(blob);_x000D_
}_x000D_
_x000D_
_x000D_
//when selecting a file on the input_x000D_
fileInput.onchange = function() {_x000D_
loadMime(fileInput.files[0], function(mime) {_x000D_
_x000D_
//print the output to the screen_x000D_
output.innerHTML = mime;_x000D_
});_x000D_
};
_x000D_
<input type="file" id="fileInput">_x000D_
<div id="output"></div>
_x000D_
It is all about preventing definitions from clashing with other code linked in to your project. It means you can keep things separate.
For example you can have one method called "run" in your code and you will still be able to call your method rather than the "run" method that has been defined in some other library that you have linked in.
I have a web page consisting of a number of vertically stacked div containers, identical in format and differing only in serial number. I wanted to hide the name anchor at the top of each div, so the most economical solution turned out to be including the anchor as an id within the opening div tag, i.e,
<div id="[serial number]" class="topic_wrapper">
may be problem in data binding in export excel . check that data properly bin to a gridview or not.
Use this code for export grid view in excel sheet and note that you must add iTextSharp dll in you project.
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
// Re-Bind data to GridView
using (CompMSEntities1 CompObj = new CompMSEntities1())
{
Start = Convert.ToDateTime(txtStart.Text);
End = Convert.ToDateTime(txtEnd.Text);
GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End);
SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result();
GridView1.DataBind();
GridView1.Visible = true;
ExportTable.Visible = true;
}
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.Style.Add(" font-size", "10px");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");
for (int i = 1; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
// row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
Just to offer the alternative to the Test-Path
cmdlet (since nobody mentioned it):
[System.IO.File]::Exists($path)
Does (almost) the same thing as
Test-Path $path -PathType Leaf
except no support for wildcard characters
Ipaper::geom_boxplot2 is just what you want.
# devtools::install_github('kongdd/Ipaper')
library(Ipaper)
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy))
p + geom_boxplot2(width = 0.8, width.errorbar = 0.5)
Starting from iOS 13 Apple has changed [deviceToken description]
output. Now it is like this {length=32,bytes=0x0b8823aec3460e1724e795cba45d22e8...af8c09f971d0dabc}
which is incorrect for device token.
I suggest to use this code snippet to resolve a problem:
+ (NSString *)stringFromDeviceToken:(NSData *)deviceToken {
NSUInteger length = deviceToken.length;
if (length == 0) {
return nil;
}
const unsigned char *buffer = deviceToken.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(length * 2)];
for (int i = 0; i < length; ++i) {
[hexString appendFormat:@"%02x", buffer[i]];
}
return [hexString copy];
}
It will work for iOS13 and lower.
You're currently writing the binary data in the string
-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.
If you want to write to a text file, the best way to do this would probably be with an ofstream
, an "out-file-stream". It behaves exactly like std::cout
, but the output is written to a file.
The following example reads one string from stdin, and then writes this string to the file output.txt
.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
std::ofstream out("output.txt");
out << input;
out.close();
return 0;
}
Note that out.close()
isn't strictly neccessary here: the deconstructor of ofstream
can handle this for us as soon as out
goes out of scope.
For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/
Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str()
. So you could use:
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
It looks like the best way to explain is that tags act as read only branches. You can use a branch as a tag, but you may inadvertently update it with new commits. Tags are guaranteed to point to the same commit as long as they exist.
There is no b['body']
in python. You have to use get_payload.
if isinstance(mailEntity.get_payload(), list):
for eachPayload in mailEntity.get_payload():
...do things you want...
...real mail body is in eachPayload.get_payload()...
else:
...means there is only text/plain part....
...use mailEntity.get_payload() to get the body...
Good Luck.
Semi-related, but this is for initializing one unique event listener specific per element.
You can use the slider to show the values in realtime, or check the console.
On the <input>
element I have a attr
tag called data-whatever
, so you can customize that data if you want to.
sliders = document.querySelectorAll("input");_x000D_
sliders.forEach(item=> {_x000D_
item.addEventListener('input', (e) => {_x000D_
console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);_x000D_
item.nextElementSibling.textContent = e.target.value;_x000D_
});_x000D_
})
_x000D_
.wrapper {_x000D_
display: flex;_x000D_
}_x000D_
span {_x000D_
padding-right: 30px;_x000D_
margin-left: 5px;_x000D_
}_x000D_
* {_x000D_
font-size: 12px_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">_x000D_
<em>50</em>_x000D_
<span>Size</span>_x000D_
<br>_x000D_
<input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">_x000D_
<em>50</em>_x000D_
<span>OriginY</span>_x000D_
<br>_x000D_
<input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">_x000D_
<em>50</em>_x000D_
<span>OriginX</span>_x000D_
</div>
_x000D_
choices = {'key1':'val1', 'key2':'val2'}
Here's the template:
<ul>
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
</ul>
Basically, .items
is a Django keyword that splits a dictionary into a list of (key, value)
pairs, much like the Python method .items()
. This enables iteration over a dictionary in a Django template.
Actually, I was also having the same problem. I was running Ubuntu. Mine problem arises because I'd lost my public key of the Ubuntu. Even updating my system was not happening. It was giving GPG error. In that case, you can regain your key by using this command:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys <key in GPG error>
After that npm works fine!
I found a better way than the proposed solutions, but it does use the background-image indeed. Compliant method (cannot confirm for IE6) Credits: http://www.kryogenix.org/code/browser/lir/
<img src="pathTo/myImage.jpg"/>
The CSS:
img[src*="pathTo/myImage.jpg"] {
background-image: url("mynewimg.jpg"); /* lets say 20x20 */
width: 20px;
display:inline-block;
padding: 20px 0 0 0;
height: 0px !important;
/* for IE 5.5's bad box model */
height /**/:20px;
}
The old image is not seen and the new is seen as expected.
The following neat solution only works for webkit
img[src*="pathTo/myImage.jpg"] {
/* note :) */
content:'';
display:inline-block;
width: 20px;
height: 20px;
background-image: url("mynewimg.jpg"); /* lets say 20x20 */
}
You don't need to add the concat package, you can do this via cssmin like this:
cssmin : {
options: {
keepSpecialComments: 0
},
minify : {
expand : true,
cwd : '/library/css',
src : ['*.css', '!*.min.css'],
dest : '/library/css',
ext : '.min.css'
},
combine : {
files: {
'/library/css/app.combined.min.css': ['/library/css/main.min.css', '/library/css/font-awesome.min.css']
}
}
}
And for js, use uglify like this:
uglify: {
my_target: {
files: {
'/library/js/app.combined.min.js' : ['/app.js', '/controllers/*.js']
}
}
}
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseThe gitlog-to-changelog
script comes in handy to generate a GNU-style ChangeLog
.
As shown by gitlog-to-changelog --help
, you may select the commits used to generate a ChangeLog
file using either the option --since
:
gitlog-to-changelog --since=2008-01-01 > ChangeLog
or by passing additional arguments after --
, which will be passed to git-log
(called internally by gitlog-to-changelog
):
gitlog-to-changelog -- -n 5 foo > last-5-commits-to-branch-foo
For instance, I am using the following rule in the top-level Makefile.am
of one of my projects:
.PHONY: update-ChangeLog
update-ChangeLog:
if test -d $(srcdir)/.git; then \
$(srcdir)/build-aux/gitlog-to-changelog \
--format='%s%n%n%b%n' --no-cluster \
--strip-tab --strip-cherry-pick \
-- $$(cat $(srcdir)/.last-cl-gen).. \
>ChangeLog.tmp \
&& git rev-list -n 1 HEAD >.last-cl-gen.tmp \
&& (echo; cat $(srcdir)/ChangeLog) >>ChangeLog.tmp \
&& mv -f ChangeLog.tmp $(srcdir)/ChangeLog \
&& mv -f .last-cl-gen.tmp $(srcdir)/.last-cl-gen \
&& rm -f ChangeLog.tmp; \
fi
EXTRA_DIST += .last-cl-gen
This rule is used at release time to update ChangeLog
with the latest not-yet-recorded commit messages. The file .last-cl-gen
contains the SHA1 identifier of the latest commit recorded in ChangeLog
and is stored in the Git repository. ChangeLog
is also recorded in the repository, so that it can be edited (e.g. to correct typos) without altering the commit messages.
A better solution for this is to
- Copy/past code of Stored Procedure
- Join that code with the table for which you want to run it again (for each row)
This was you get a clean table-formatted output. While if you run SP for every row, you get a separate query result for each iteration which is ugly.
Just something to watch out for......
In SQL Server 2008 R2 SSMS, the "Script Constraint as -> DROP And CREATE To" command produces T-SQL like below
USE [MyDatabase]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DEF_Detail_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [Patient].[Detail] DROP CONSTRAINT [DEF_Detail_IsDeleted]
END
GO
USE [MyDatabase]
GO
ALTER TABLE [Patient].[Detail] ADD CONSTRAINT [DEF_Detail_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]
GO
Out of the box, this script does NOT drop the constraint because the SELECT returns 0 rows. (see post Microsoft Connect).
The name of the default constraint is wrong but I gather it also has something to do with the OBJECT_ID function because changing the name doesn't fix the problem.
To fix this, I removed the usage of OBJECT_ID and used the default constraint name instead.
(SELECT * FROM dbo.sysobjects WHERE [name] = (N'DEF_Detail_IsDeleted') AND type = 'D')
I strongly recommend using lowercase field|column names, it will make your life easier.
Let's assume you have a table called users with the following definition and records:
id|firstname|lastname|username |password
1 |joe |doe |[email protected] |1234
2 |jane |doe |[email protected] |12345
3 |johnny |doe |[email protected]|123456
let's say you want to get all records from table users, then you do:
SELECT * FROM users;
Now let's assume you want to select all records from table users, but you're interested only in the fields id, firstname and lastname, thus ignoring username and password:
SELECT id, firstname, lastname FROM users;
Now we get at the point where you want to retrieve records based on condition(s), what you need to do is to add the WHERE clause, let's say we want to select from users only those that have username = [email protected] and password = 1234, what you do is:
SELECT * FROM users
WHERE ( ( username = '[email protected]' ) AND ( password = '1234' ) );
But what if you need only the id of a record with username = [email protected] and password = 1234? then you do:
SELECT id FROM users
WHERE ( ( username = '[email protected]' ) AND ( password = '1234' ) );
Now to get to your question, as others before me answered you can use the IN clause:
SELECT * FROM users
WHERE ( id IN (1,2,..,n) );
or, if you wish to limit to a list of records between id 20 and id 40, then you can easily write:
SELECT * FROM users
WHERE ( ( id >= 20 ) AND ( id <= 40 ) );
I hope this gives a better understanding.
If you just want to update the property on all elements then
someList.All(x => { x.SomeProp = "foo"; return true; })
In LINQ2SQL you seldom need to join explicitly when using inner joins.
If you have proper foreign key relationships in your database you will automatically get a relation in the LINQ designer (if not you can create a relation manually in the designer, although you should really have proper relations in your database)
Then you can just access related tables with the "dot-notation"
var q = from child in context.Childs
where child.Parent.col2 == 4
select new
{
childCol1 = child.col1,
parentCol1 = child.Parent.col1,
};
will generate the query
SELECT [t0].[col1] AS [childCol1], [t1].[col1] AS [parentCol1]
FROM [dbo].[Child] AS [t0]
INNER JOIN [dbo].[Parent] AS [t1] ON ([t1].[col1] = [t0].[col1]) AND ([t1].[col2] = [t0].[col2])
WHERE [t1].[col2] = @p0
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [4]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1
In my opinion this is much more readable and lets you concentrate on your special conditions and not the actual mechanics of the join.
Edit
This is of course only applicable when you want to join in the line with our database model. If you want to join "outside the model" you need to resort to manual joins as in the answer from Quintin Robinson
I would prefer to keep the "Show Whitespace" button on the toolbar, so that in one click you can toggle it.
Go to Window -> Perspective -> Customize Perspective and enable to show the button on toolbar.
View Demo which is using angularjs
and see your's browser log
<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body>
</body>
<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {
console.log('starting run');
// Timeout timer value
var TimeOutTimerValue = 5000;
// Start a timeout
var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
var bodyElement = angular.element($document);
/// Keyboard Events
bodyElement.bind('keydown', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('keyup', function (e) { TimeOut_Resetter(e) });
/// Mouse Events
bodyElement.bind('click', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousemove', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('DOMMouseScroll', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousewheel', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousedown', function (e) { TimeOut_Resetter(e) });
/// Touch Events
bodyElement.bind('touchstart', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('touchmove', function (e) { TimeOut_Resetter(e) });
/// Common Events
bodyElement.bind('scroll', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('focus', function (e) { TimeOut_Resetter(e) });
function LogoutByTimer()
{
console.log('Logout');
///////////////////////////////////////////////////
/// redirect to another page(eg. Login.html) here
///////////////////////////////////////////////////
}
function TimeOut_Resetter(e)
{
console.log('' + e);
/// Stop the pending timeout
$timeout.cancel(TimeOut_Thread);
/// Reset the timeout
TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
}
})
</script>
</html>
Below code is pure javascript version
<html>
<head>
<script type="text/javascript">
function logout(){
console.log('Logout');
}
function onInactive(millisecond, callback){
var wait = setTimeout(callback, millisecond);
document.onmousemove =
document.mousedown =
document.mouseup =
document.onkeydown =
document.onkeyup =
document.focus = function(){
clearTimeout(wait);
wait = setTimeout(callback, millisecond);
};
}
</script>
</head>
<body onload="onInactive(5000, logout);"></body>
</html>
I updated my solution as @Tom suggestion.
<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body>
</body>
<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {
console.log('starting run');
// Timeout timer value
var TimeOutTimerValue = 5000;
// Start a timeout
var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
var bodyElement = angular.element($document);
angular.forEach(['keydown', 'keyup', 'click', 'mousemove', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'scroll', 'focus'],
function(EventName) {
bodyElement.bind(EventName, function (e) { TimeOut_Resetter(e) });
});
function LogoutByTimer(){
console.log('Logout');
///////////////////////////////////////////////////
/// redirect to another page(eg. Login.html) here
///////////////////////////////////////////////////
}
function TimeOut_Resetter(e){
console.log(' ' + e);
/// Stop the pending timeout
$timeout.cancel(TimeOut_Thread);
/// Reset the timeout
TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
}
})
</script>
</html>
'Create or replace table' is not possible. As others stated, you can write a procedure and/or use begin execute immediately (...). Because I don't see an answer with how to (re)create the table, I putted a script as an answer.
PS: in line of what jeffrey-kemp mentioned: this beneath script will NOT save data that is already present in the table you are going to drop. Because of the risk of loosing data, at our company it is only allowed to alter existing tables on the production environment, and it is not allowed to drop tables. By using the drop table statement, sooner or later you will get the company police standing at your desk.
--Create the table 'A_TABLE_X', and drop the table in case it already is present
BEGIN
EXECUTE IMMEDIATE
'
CREATE TABLE A_TABLE_X
(
COLUMN1 NUMBER(15,0),
COLUMN2 VARCHAR2(255 CHAR),
COLUMN3 VARCHAR2(255 CHAR)
)';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -955 THEN -- ORA-00955: object name already used
EXECUTE IMMEDIATE 'DROP TABLE A_TABLE_X';
END IF;
END;
you will need to button initilzation inside method instead of trying to initlzing View's at class level do it as:
Button button; //<< declare here..
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.standingsButton); //<< initialize here
// set OnClickListener for Button here
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,StandingsActivity.class));
}
});
}
Not sure how to get the IP address specifically, but the location object provides part of the answer.
e.g. these variables might be helpful:
self.location.host
- Sets or retrieves the hostname and port number of the locationself.location.hostname
- Sets or retrieves the host name part of
the location or URL.this can help to evaluate http status
var=`curl -I http://www.example.org 2>/dev/null | head -n 1 | awk -F" " '{print $2}'`
echo http:$var
Since Node v11.0.0 fs promises are available natively without promisify
:
const fs = require('fs').promises;
async function loadMonoCounter() {
const data = await fs.readFile("monolitic.txt", "binary");
return new Buffer(data);
}
One of these will work...
<head>_x000D_
<meta http-equiv='refresh' content='0; URL=http://example.com/'>_x000D_
</head>
_x000D_
...or it can done with JavaScript:
window.location.href = 'https://example.com/';
_x000D_
Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:
Example:
POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"
content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"
content of picture_of_sunset.jpg ...
--12345--
I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:
POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde
--abcde
Content-Disposition: file; file="picture.jpg"
content of jpg...
--abcde
Content-Disposition: file; file="test.py"
content of test.py file ....
--abcde--
--12345--
Take a look at the link above.
In Python you don't use getters or setters or properties just for the fun of it. You first just use attributes and then later, only if needed, eventually migrate to a property without having to change the code using your classes.
There is indeed a lot of code with extension .py that uses getters and setters and inheritance and pointless classes everywhere where e.g. a simple tuple would do, but it's code from people writing in C++ or Java using Python.
That's not Python code.
As of ECMAScript 6, you can use Array.prototype.find
for this. This is implemented and working in Firefox (25.0), Chrome (45.0), Edge (12), and Safari (7.1), but not in Internet Explorer or a bunch of other old or uncommon platforms.
For example, x
below is 106
:
const x = [100,101,102,103,104,105,106,107,108,109].find(function (el) {
return el > 105;
});
console.log(x);
_x000D_
If you want to use this right now but need support for IE or other unsupporting browsers, you can use a shim. I recommend the es6-shim. MDN also offers a shim if for some reason you don't want to put the whole es6-shim into your project. For maximum compatibility you want the es6-shim, because unlike the MDN version it detects buggy native implementations of find
and overwrites them (see the comment that begins "Work around bugs in Array#find and Array#findIndex" and the lines immediately following it).
This answer will cover most of the scenario. I can across this situation when user try to copy paste the phone number
$('#help_number').keyup(function(){
$(this).val().match(/\d+/g).join("")
});
Explanation:
str= "34%^gd 5-67 6-6ds"
str.match(/\d+/g)
It will give a array of string as output >> ["34", "56766"]
str.match(/\d+/g).join("")
join will convert and concatenate that array data into single string
output >> "3456766"
In my example I need the output as 209-356-6788 so I used replace
$('#help_number').keyup(function(){
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
According to the Git Cheatsheet you have to create the branch first
git branch [branchName]
and then
git checkout [branchName]
This may help some people who still have problems.
I use Visual Studio 2015 and I could only pass the arguments when I changed the definition of argv
.
Instead of
int main(int argc, char **argv){
}
I had to use
int main(int argc, char *argv[]){
}
I do not know why it was necessary, but it works.
in visual studio for vb.net, go to the project properties, click Add Resource > Existing File, select your Icon.
in your code:
Me.Icon = My.Resources.IconResourceName
HTML5 defined a window.saveAs(blob, filename)
method. It isn't supported by any browser right now. But there is a compatibility library called FileSaver.js that adds this function to most modern browsers (including Internet Explorer 10+). Internet Explorer 10 supports a navigator.msSaveBlob(blob, filename)
method (MSDN), which is used in FileSaver.js for Internet Explorer support.
I wrote a blog posting with more details about this problem.
To manipulate data you actually need executeUpdate()
rather than executeQuery()
.
Here's an extract from the executeUpdate()
javadoc which is already an answer at its own:
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
changed distrubutionUrl from 4.1 to 4.4
changed build gradle version to 3.1.1 under project/android
works for me.
updated on May 26-2018
If the external library is in a folder that is under the project then
File -> Settings -> Project -> Project structure -> select the folder and Mark as Sources!
If not, add content root, and do similar things.
os.path.exists
will also return True
if there's a regular file with that name.
os.path.isdir
will only return True
if that path exists and is a directory, or a symbolic link to a directory.
var q = from b in listOfBoxes
group b by b.Owner into g
select new
{
Owner = g.Key,
Boxes = g.Count(),
TotalWeight = g.Sum(item => item.Weight),
TotalVolume = g.Sum(item => item.Volume)
};
Here a working example to use slf4j as façade with log4j in the backend:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xxx</groupId>
<artifactId>xxx</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.3</version>
</dependency>
</dependencies>
</project>
src/main/resources/log4j.properties
# Root logger option
log4j.rootLogger=DEBUG, stdout
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
src/main/java/Main.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
/**
* Default private constructor.
*/
private Main() {
}
/**
* Main method.
*
* @param args Arguments passed to the execution of the application
*/
public static void main(final String[] args) {
logger.info("Message to log");
}
}
You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:
if ([category isEqualToString:@"Some String"])
{
// Both strings are equal without respect to their case.
}
Case-insensitive is like this:
if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
// Both strings are equal with respect to their case.
}
Thunks versus Sagas
Redux-Thunk
and Redux-Saga
differ in a few important ways, both are middleware libraries for Redux (Redux middleware is code that intercepts actions coming into the store via the dispatch() method).
An action can be literally anything, but if you're following best practices, an action is a plain javascript object with a type field, and optional payload, meta, and error fields. e.g.
const loginRequest = {
type: 'LOGIN_REQUEST',
payload: {
name: 'admin',
password: '123',
}, };
Redux-Thunk
In addition to dispatching standard actions, Redux-Thunk
middleware allows you to dispatch special functions, called thunks
.
Thunks (in Redux) generally have the following structure:
export const thunkName =
parameters =>
(dispatch, getState) => {
// Your application logic goes here
};
That is, a thunk
is a function that (optionally) takes some parameters and returns another function. The inner function takes a dispatch function
and a getState
function -- both of which will be supplied by the Redux-Thunk
middleware.
Redux-Saga
Redux-Saga
middleware allows you to express complex application logic as pure functions called sagas. Pure functions are desirable from a testing standpoint because they are predictable and repeatable, which makes them relatively easy to test.
Sagas are implemented through special functions called generator functions. These are a new feature of ES6 JavaScript
. Basically, execution jumps in and out of a generator everywhere you see a yield statement. Think of a yield
statement as causing the generator to pause and return the yielded value. Later on, the caller can resume the generator at the statement following the yield
.
A generator function is one defined like this. Notice the asterisk after the function keyword.
function* mySaga() {
// ...
}
Once the login saga is registered with Redux-Saga
. But then the yield
take on the the first line will pause the saga until an action with type 'LOGIN_REQUEST'
is dispatched to the store. Once that happens, execution will continue.
Preferred way to change the appearance/whatever of row views once the ListView is drawn is to change something in the data ListView draws from (the array of objects that is passed into your Adapter) and make sure to account for that in your getView() function, then redraw the ListView by calling
notifyDataSetChanged();
EDIT: while there is a way to do this, if you need to do this chances are doing something wrong. While are few edge cases I can think about, generally using notifyDataSetChanged()
and other built in mechanisms is a way to go.
EDIT 2: One of the common mistakes people make is trying to come up with their own way to respond to user clicking/selecting a row in the ListView, as in one of the comments to this post. There is an existing way to do this. Here's how:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/* Parameters
parent: The AdapterView where the click happened.
view: The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position: The position of the view in the adapter.
id: The row id of the item that was clicked. */
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//your code here
}
});
ListView has a lot of build-in functionality and there is no need to reinvent the wheel for simpler cases. Since ListView extends AdapterView, you can set the same Listeners, such as OnItemClickListener as in the example above.
See http://msdn.microsoft.com/en-us/library/ms187928.aspx
You can concatenate it:
SELECT CONVERT(VARCHAR(10), GETDATE(), 104) + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)
With all due respect to our unknown (yahoo) poster, I look at code like that and just die a little inside. Alphabet soup is just so insanely difficult to debug. A single typo anywhere in there can really ruin your whole day. Sadly, this particular example lacked variables with underscores. It's so much more fun when we have a_b-c_d*e_f-g_h. Especially when using a font where _ and - have the same pixel length.
Taking up Suvesh Pratapa on his suggestion, I note:
Given 3x3 matrix:
y0x0 y0x1 y0x2
y1x0 y1x1 y1x2
y2x0 y2x1 y2x2
Declared as double matrix [/*Y=*/3] [/*X=*/3];
(A) When taking a minor of a 3x3 array, we have 4 values of interest. The lower X/Y index is always 0 or 1. The higher X/Y index is always 1 or 2. Always! Therefore:
double determinantOfMinor( int theRowHeightY,
int theColumnWidthX,
const double theMatrix [/*Y=*/3] [/*X=*/3] )
{
int x1 = theColumnWidthX == 0 ? 1 : 0; /* always either 0 or 1 */
int x2 = theColumnWidthX == 2 ? 1 : 2; /* always either 1 or 2 */
int y1 = theRowHeightY == 0 ? 1 : 0; /* always either 0 or 1 */
int y2 = theRowHeightY == 2 ? 1 : 2; /* always either 1 or 2 */
return ( theMatrix [y1] [x1] * theMatrix [y2] [x2] )
- ( theMatrix [y1] [x2] * theMatrix [y2] [x1] );
}
(B) Determinant is now: (Note the minus sign!)
double determinant( const double theMatrix [/*Y=*/3] [/*X=*/3] )
{
return ( theMatrix [0] [0] * determinantOfMinor( 0, 0, theMatrix ) )
- ( theMatrix [0] [1] * determinantOfMinor( 0, 1, theMatrix ) )
+ ( theMatrix [0] [2] * determinantOfMinor( 0, 2, theMatrix ) );
}
(C) And the inverse is now:
bool inverse( const double theMatrix [/*Y=*/3] [/*X=*/3],
double theOutput [/*Y=*/3] [/*X=*/3] )
{
double det = determinant( theMatrix );
/* Arbitrary for now. This should be something nicer... */
if ( ABS(det) < 1e-2 )
{
memset( theOutput, 0, sizeof theOutput );
return false;
}
double oneOverDeterminant = 1.0 / det;
for ( int y = 0; y < 3; y ++ )
for ( int x = 0; x < 3; x ++ )
{
/* Rule is inverse = 1/det * minor of the TRANSPOSE matrix. *
* Note (y,x) becomes (x,y) INTENTIONALLY here! */
theOutput [y] [x]
= determinantOfMinor( x, y, theMatrix ) * oneOverDeterminant;
/* (y0,x1) (y1,x0) (y1,x2) and (y2,x1) all need to be negated. */
if( 1 == ((x + y) % 2) )
theOutput [y] [x] = - theOutput [y] [x];
}
return true;
}
And round it out with a little lower-quality testing code:
void printMatrix( const double theMatrix [/*Y=*/3] [/*X=*/3] )
{
for ( int y = 0; y < 3; y ++ )
{
cout << "[ ";
for ( int x = 0; x < 3; x ++ )
cout << theMatrix [y] [x] << " ";
cout << "]" << endl;
}
cout << endl;
}
void matrixMultiply( const double theMatrixA [/*Y=*/3] [/*X=*/3],
const double theMatrixB [/*Y=*/3] [/*X=*/3],
double theOutput [/*Y=*/3] [/*X=*/3] )
{
for ( int y = 0; y < 3; y ++ )
for ( int x = 0; x < 3; x ++ )
{
theOutput [y] [x] = 0;
for ( int i = 0; i < 3; i ++ )
theOutput [y] [x] += theMatrixA [y] [i] * theMatrixB [i] [x];
}
}
int
main(int argc, char **argv)
{
if ( argc > 1 )
SRANDOM( atoi( argv[1] ) );
double m[3][3] = { { RANDOM_D(0,1e3), RANDOM_D(0,1e3), RANDOM_D(0,1e3) },
{ RANDOM_D(0,1e3), RANDOM_D(0,1e3), RANDOM_D(0,1e3) },
{ RANDOM_D(0,1e3), RANDOM_D(0,1e3), RANDOM_D(0,1e3) } };
double o[3][3], mm[3][3];
if ( argc <= 2 )
cout << fixed << setprecision(3);
printMatrix(m);
cout << endl << endl;
SHOW( determinant(m) );
cout << endl << endl;
BOUT( inverse(m, o) );
printMatrix(m);
printMatrix(o);
cout << endl << endl;
matrixMultiply (m, o, mm );
printMatrix(m);
printMatrix(o);
printMatrix(mm);
cout << endl << endl;
}
You may also want to detect very large determinants as round-off errors will affect your accuracy!
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
You are in the "Output" tab instead of the Terminal. The output tab is actually only for you to read from.
Press F5
to begin Debugging
and it'll bring you into the Terminal tab.
The terminal is interactive, so you can read output AND type back. It is indeed a console prompt/ terminal (hence its name).
This works well enough for me :)
// deg2rad * degrees = radians
#define deg2rad (3.14159265/180.0)
// rad2deg * radians = degrees
#define rad2deg (180/3.14159265)
I had faced the same problem while accessing any hard drive directory. Then I solved it in this way.
import os
os.startfile("D:\folder_name\file_name") #running shortcut
os.startfile("F:") #accessing directory
The picture above shows an error and resolved output.
I have also been through this problem,
First i tried setting my password of root to blank using command :
SET PASSWORD FOR root@localhost=PASSWORD('');
But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.
SET PASSWORD FOR [email protected]=PASSWORD('');
Just replace localhost with 127.0.0.1 and you are done .
protected void btnSave_Click(object sender, EventArgs e)
{
var FullName = "stackoverflow"
char[] charArray = FullName.ToLower().ToCharArray();
Dictionary<char, int> counter = new Dictionary<char, int>();
int tempVar = 0;
foreach (var item in charArray)
{
if (counter.TryGetValue(item, out tempVar))
{
counter[item] += 1;
}
else
{
counter.Add(item, 1);
}
}
//var numberofchars = "";
foreach (KeyValuePair<char, int> item in counter)
{
if (counter.Count > 0)
{
//Label1.Text=split(item.
}
Response.Write(item.Value + " " + item.Key + "<br />");
// Label1.Text=item.Value + " " + item.Key + "<br />";
spnDisplay.InnerText= item.Value + " " + item.Key + "<br />";
}
}
Expanding S.Lott's answer so that new items are processed as well:
todo = myarr
done = []
while todo:
added = []
for a in todo:
if somecond(a):
added.append(newObj())
done.extend(todo)
todo = added
The final list is in done
.
It will impact your script if you work with multi-byte text that you substring from. If this is the case, I higly recommend enabling mb_* functions in your php.ini or do this ini_set("mbstring.func_overload", 2);
$string = "'test1', 'test2', 'test3',";_x000D_
echo mb_substr($string, 0, -1);
_x000D_
My solution is a bit different:
$( 'input[name="your_radio_input_name"]:radio:first' ).click();
You also can use Gnuplot
which is also available from gretl
. Put your x y z data on a text file an insert the following
splot 'test.txt' using 1:2:3 with points palette pointsize 3 pointtype 7
Then you can set labels, etc. using
set xlabel "xxx" rotate parallel
set ylabel "yyy" rotate parallel
set zlabel "zzz" rotate parallel
set grid
show grid
unset key
In addition to File.ReadAllText
, File.ReadAllLines
, and File.WriteAllText
(and similar helpers from File
class) shown in another answer you can use StreamWriter
/StreamReader
classes.
Writing a text file:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}
Reading a text file:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
string readText = readtext.ReadLine();
}
Notes:
readtext.Dispose()
instead of using
, but it will not close file/reader/writer in case of exceptionsusing
/Close
is very common reason of "why data is not written to file".On Fedora, this works:
yum install lapack lapack-devel blas blas-devel
pip install numpy
pip install scipy
Remember to install 'lapack-devel' and 'blas-devel' in addition to 'blas' and 'lapack' otherwise you'll get the error you mentioned or the "numpy.distutils.system_info.LapackNotFoundError" error.
"List" is an object getting from backend and using iterator to display in table
"minAmount" , "MaxAmount" is an object variable "mrr" is an just temporary var to get value and iterate mrr to get data.
<table class="table table-hover">
<tbody>
<tr th:each="mrr,iterStat : ${list}">
<td th:text="${mrr.id}"></td>
<td th:text="${mrr.minAmount}"></td>
<td th:text="${mrr.maxAmount}"></td>
</tr>
</tbody>
</table>
I'm a bit stumped, not sure if this was due to an HTTP output caching issue.
Anyways, "all of a sudden it started working properly". :/ So, the example above worked without me adding or changing anything.
Guess the code just had to sit and cook overnight... :)
Thanks for helping, guys!
While it may not directly determine whether the phone is connected to a network, the simplest(, cleanest?) solution would be to 'ping' Google, or some other server, (which isn't possible unless the phone is connected to a network):
private var urlSession:URLSession = {
var newConfiguration:URLSessionConfiguration = .default
newConfiguration.waitsForConnectivity = false
newConfiguration.allowsCellularAccess = true
return URLSession(configuration: newConfiguration)
}()
public func canReachGoogle() -> Bool
{
let url = URL(string: "https://8.8.8.8")
let semaphore = DispatchSemaphore(value: 0)
var success = false
let task = urlSession.dataTask(with: url!)
{ data, response, error in
if error != nil
{
success = false
}
else
{
success = true
}
semaphore.signal()
}
task.resume()
semaphore.wait()
return success
}
If you're concerned that the server may be down or may block your IP, you can always ping multiple servers in a similar fashion and return whether any of them are reachable. Or have someone set up a dedicated server just for this purpose.
I had the same problem and I found this solution working with bindParam :
bindParam(':param', $myvar = NULL, PDO::PARAM_INT);
An empty array is falsey in PHP, so you don't even need to use empty()
as others have suggested.
<?php
$playerList = array();
if (!$playerList) {
echo "No players";
} else {
echo "Explode stuff...";
}
// Output is: No players
PHP's empty()
determines if a variable doesn't exist or has a falsey value (like array()
, 0
, null
, false
, etc).
In most cases you just want to check !$emptyVar
. Use empty($emptyVar)
if the variable might not have been set AND you don't wont to trigger an E_NOTICE
; IMO this is generally a bad idea.
For netbeans 8.2
1. First run command as administrator.
2. set path to you downloads folder using cd 'location to the downloads folder'
3. extract using netbeans-8.2-windows.exe --extract command
4. run java -jar bundle.jar
5. Done :)
You need to install the Visual C++ libraries: http://www.microsoft.com/en-us/download/details.aspx?id=30679
If you have an Activity
object hanging around, you can use the isDestroyed()
method:
Activity activity;
// ...
if (!activity.isDestroyed()) {
// ...
}
This is nice if you have a non-anonymous AsyncTask
subclass that you use in various places.
In react native, I had the error not show maps and close app, run adb logcat and show error within console:
java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion
fix it by adding within androidManifest.xml
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
The shortest and laziest (without casting) solution would be to use the formula:
SELECT COUNT(myCol OR NULL) FROM myTable;
Try it yourself:
SELECT COUNT(x < 7 OR NULL)
FROM GENERATE_SERIES(0,10) t(x);
gives the same result than
SELECT SUM(CASE WHEN x < 7 THEN 1 ELSE 0 END)
FROM GENERATE_SERIES(0,10) t(x);
You can also check single value in multiple arrays like,
if (grep /$match/, @array, @array_one, @array_two, @array_Three)
{
print "found it\n";
}
Based on comment of @alessandro-pezzato.
Run multiples commands by using &
between the commands.
Example:
$ sleep 3 & sleep 5 & sleep 2 &
It's will execute the commands in background.
Map.Entry
is a key and its value combined into one class. This allows you to iterate over Map.entrySet()
instead of having to iterate over Map.keySet()
, then getting the value for each key. A better way to write what you have is:
for (Map.Entry<String, JButton> entry : listbouton.entrySet())
{
String key = entry.getKey();
JButton value = entry.getValue();
this.add(value);
}
If this wasn't clear let me know and I'll amend my answer.
Generally speaking, terms like exceptions, faults, aborts, Traps, and Interrupts all mean the same thing and are called "Interrupts".
Coming to the difference between Trap and Interrupt:
Trap: Is a programmer initiated and expected transfer of control to a special handler routine. (For ex: 80x86 INT instruction is a good example)
Where as
Interrupt(Hardware): Is a program control interruption based on an external hardware event external to the CPU (For ex: Pressing a key on the keyboard or a time out on a timer chip)
You could try using HTML5s sessionStorage it lasts for the duration on the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
sessionStorage.setItem("username", "John");
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage
Browser Compatibility https://code.google.com/p/sessionstorage/ compatible with every A-grade browser, included iPhone or Android. http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
Check that your singing identity IN YOUR TARGET properties is correct. This one over-rides what you have in your project properties.
Also: I dunno if this is true - but I wasn't getting emails detailing my binary rejections when I did the "ready for binary upload" from a PC - but I DID get an email when I did this on the MAC
For anyone looking for a regex:
const BLACKLIST = /[<>:"\/\\|?*]/g;
Name
can also be set using property element syntax with inner text, but that is uncommon. In contrast, x:Name
cannot be set in XAML
property element syntax, or in code using SetValue
; it can only be set using attribute syntax on objects because it is a directive.
If Name
is available as a property on the class, Name
and x:Name
can be used interchangeably as attributes, but a parse exception will result if both are specified on the same element. If the XAML is markup compiled, the exception will occur on the markup compile, otherwise it occurs on load.
I'm going to improve the answer by supporting partitioned tables:
find partition scheme and partition key using below scritps:
declare @partition_scheme varchar(100) = (
select distinct ps.Name AS PartitionScheme
from sys.indexes i
join sys.partitions p ON i.object_id=p.object_id AND i.index_id=p.index_id
join sys.partition_schemes ps on ps.data_space_id = i.data_space_id
where i.object_id = object_id('your table name')
)
print @partition_scheme
declare @partition_column varchar(100) = (
select c.name
from sys.tables t
join sys.indexes i
on(i.object_id = t.object_id
and i.index_id < 2)
join sys.index_columns ic
on(ic.partition_ordinal > 0
and ic.index_id = i.index_id and ic.object_id = t.object_id)
join sys.columns c
on(c.object_id = ic.object_id
and c.column_id = ic.column_id)
where t.object_id = object_id('your table name')
)
print @partition_column
then change the generation query by adding below line at the right place:
+ IIF(@partition_scheme is null, '', 'ON [' + @partition_scheme + ']([' + @partition_column + '])')
It seems the solutions for HTML/JS/CSS desktop apps are in no short supply.
One solution I have just come across is TideSDK: http://www.tidesdk.org/, which seems very promising, looking at the documentation.
You can develop with Python, PHP or Ruby, and package it for Mac, Windows or Linux.
You can try,
<div asp-validation-summary="All" class="text-danger"></div>
You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.
Make sure that all functions with non-void return type have a return
statement.
While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.
I am building an application that will run in a data center. It should not generate any errors or raise any exceptions. My data center has a network monitoring system, which includes an SNMP trap receiver.
try:
main()
except as e:
log(str(e))
send_snmp_trap(str(e))
raise
except that raise isn't going to go anywhere because it's and the bottom of any stack that might be left.
BTW, this is not a universal panacea by any means. There are some exceptions that can't be caught. SNMP doesn't guarantee delivery. YMMV.
Quickest way to convert .ui to .py is from terminal:
pyuic4 -x input.ui -o output.py
Make sure you have pyqt4-dev-tools installed.
//query is your json
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://my.site/test/v1/product/search?qy=");
StringEntity input = new StringEntity(query, "UTF-8");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response=response = httpClient.execute(postRequest);
Another way to solve this using xpath
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath(//*[@id='email'])).sendKeys("[email protected]");
Hope that will help. :)
You can use a post-commit hook.
Put the post-commit hook script in the hooks
folder, create a wget_folder
in your C:\ drive, and put the wget.exe
file in this folder.
Add the following code in the file called post-commit.bat
SET REPOS=%1
SET REV=%2
FOR /f "tokens=*" %%a IN (
'svnlook uuid %REPOS%'
) DO (
SET UUID=%%a
)
FOR /f "tokens=*" %%b IN (
'svnlook changed --revision %REV% %REPOS%'
) DO (
SET POST=%%b
)
echo %REPOS% ----- 1>&2
echo %REV% -- 1>&2
echo %UUID% --1>&2
echo %POST% --1>&2
C:\wget_folder\wget ^
--header="Content-Type:text/plain" ^
--post-data="%POST%" ^
--output-document="-" ^
--timeout=2 ^
http://localhost:9090/job/Test/build/%UUID%/notifyCommit?rev=%REV%
where Test = name of the job
echo
is used to see the value and you can also add exit 2
at the end to know about the issue and whether the post-commit hook script is running or not.
You can use SHOW
:
SHOW max_connections;
This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf
as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf
in your current session:
RESET max_connections;
However, not applicable to this particular setting. The manual:
This parameter can only be set at server start.
To see all settings:
SHOW ALL;
There is also pg_settings
:
The view
pg_settings
provides access to run-time parameters of the server. It is essentially an alternative interface to theSHOW
andSET
commands. It also provides access to some facts about each parameter that are not directly available fromSHOW
, such as minimum and maximum values.
For your original request:
SELECT *
FROM pg_settings
WHERE name = 'max_connections';
Finally, there is current_setting()
, which can be nested in DML statements:
SELECT current_setting('max_connections');
Related:
The HttpContext.Current.User.Identity.Name returns null
This depends on whether the authentication mode is set to Forms or Windows in your web.config file.
For example, if I write the authentication like this:
<authentication mode="Forms"/>
Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:
<authentication mode="Windows"/>
I can run the application again and check for the username, and I will get the username successfully.
For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.
Edited on 2014/8/25: Here was where I forked it.
Thanks @anvarik.
Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @
<div ng-controller="MyCtrl">
<h2>Parent Scope</h2>
<input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>
<br><br>
<!-- attribute-foo binds to a DOM attribute which is always
a string. That is why we are wrapping it in curly braces so
that it can be interpolated. -->
<my-component attribute-foo="{{foo}}" binding-foo="foo"
isolated-expression-foo="updateFoo(newFoo)" >
<h2>Attribute</h2>
<div>
<strong>get:</strong> {{isolatedAttributeFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedAttributeFoo">
<i>// This does not update the parent scope.</i>
</div>
<h2>Binding</h2>
<div>
<strong>get:</strong> {{isolatedBindingFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedBindingFoo">
<i>// This does update the parent scope.</i>
</div>
<h2>Expression</h2>
<div>
<input ng-model="isolatedFoo">
<button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
<i>// And this calls a function on the parent scope.</i>
</div>
</my-component>
</div>
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'@attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.foo = 'Hello!';
$scope.updateFoo = function (newFoo) {
$scope.foo = newFoo;
}
}]);
PowerShell 3.0 now supports for credentials on the FileSystem provider. To use alternate credentials, simply use the Credential parameter on the New-PSDrive cmdlet
PS > New-PSDrive -Name J -PSProvider FileSystem -Root \\server001\sharename -Credential mydomain\travisj -Persist
After this command you can now access the newly created drive and do other operations including copy or move files like normal drive. here is the full solution:
$Source = "C:\Downloads\myfile.txt"
$Dest = "\\10.149.12.162\c$\skumar"
$Username = "administrator"
$Password = ConvertTo-SecureString "Complex_Passw0rd" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential($Username, $Password)
New-PSDrive -Name J -PSProvider FileSystem -Root $Dest -Credential $mycreds -Persist
Copy-Item -Path $Source -Destination "J:\myfile.txt"
To update @cdescours' answer, uploaded builds can now be seen in the "Activity" tab in "Processing" state.
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});
Try this one as it worked for me:
SSIS - the value cannot be converted because of a potential loss of data
A classic "or" would be |
. For example, ab|de
would match either side of the expression.
However, for something like your case you might want to use the ?
quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:
\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+
This pattern will match:
\d+
: One or more numbers.\s+
: One or more whitespaces.[A-Z\s]+
: One or more uppercase characters or space characters\s+
: One or more whitespaces.[A-Z][A-Za-z\s]+
: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.If you'd like a more static check, e.g. indeed only match ABC
and A ABC
, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):
\d (?:ABC|A ABC) Street
Or another alternative using a quantifier:
\d (?:A )?ABC Street
if you give it 234.545332233 it will give you 234.54
let textData = Double(myTextField.text!)!
let text = String(format: "%.2f", arguments: [textData])
mylabel.text = text
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
You forgot the return types in your member function definitions:
int ttTree::ttTreeInsert(int value) { ... }
^^^
and so on.
You need to put the format arguments into a tuple (add parentheses):
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)
What you currently have is equivalent to the following:
intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl
Example:
>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'
C++11/Linux version:
#include <dirent.h>
if (auto dir = opendir("some_dir/")) {
while (auto f = readdir(dir)) {
if (!f->d_name || f->d_name[0] == '.')
continue; // Skip everything that starts with a dot
printf("File: %s\n", f->d_name);
}
closedir(dir);
}
using a function:
function run_command ($command)
{
invoke-expression "$command *>$null"
return $_
}
if (!(run_command "dir *.txt"))
{
if (!(run_command "dir *.doc"))
{
run_command "dir *.*"
}
}
or if you like one-liners:
function run_command ($command) { invoke-expression "$command "|out-null; return $_ }
if (!(run_command "dir *.txt")) { if (!(run_command "dir *.doc")) { run_command "dir *.*" } }
But that doesn't seem like the proper way to do it..
That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.
Example:
const promises = [_x000D_
new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
.then(data => {_x000D_
console.log("First handler", data);_x000D_
return data.map(entry => entry * 10);_x000D_
})_x000D_
.then(data => {_x000D_
console.log("Second handler", data);_x000D_
});
_x000D_
(catch
handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)
The output we see from that is:
First handler [1,2] Second handler [10,20]
...because the first handler gets the resolution of the two promises (1
and 2
) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.
If the additional work you're doing is synchronous, you can also put it in the first handler:
Example:
const promises = [_x000D_
new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
.then(data => {_x000D_
console.log("Initial data", data);_x000D_
data = data.map(entry => entry * 10);_x000D_
console.log("Updated data", data);_x000D_
return data;_x000D_
});
_x000D_
...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.
String str, str1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String : ");
str = sc.nextLine();
str1 = str.replaceAll("[aeiouAEIOU]", "");
System.out.print(str1);
Time to contribute now. I am sysadmin role and worked on getting two public access users to execute xp_cmdshell. I am able to execute xp_cmdshell but not the two users.
I did the following steps:
create new role:
use master
CREATE ROLE [CmdShell_Executor] AUTHORIZATION [dbo]
GRANT EXEC ON xp_cmdshell TO [CmdShell_Executor]
add users in master database: Security --> Users. Membership checks only [CmdShell_Executor] that is just created
set up proxy account:
EXEC sp_xp_cmdshell_proxy_account 'domain\user1','users1 Windows password'
EXEC sp_xp_cmdshell_proxy_account 'domain\user2','users2 Windows password'
Then both users can execute the stored procedure that contains xp_cmdshell invoking a R script run. I let the users come to my PC to type in the password, execute the one line code, then delete the password.
I had the same problem. When I tried the accepted answer (rockyb), I got the message that the package was already installed and assigned to my project. When I checked the references list, it was NOT referenced, however.
The Microsoft.Web.Infrastructure was installed in my solution's packages folder. Instead of using NuGet to add the package, I just used the Add Reference option. On the left side of the pop-up window, I chose Browse, and then pressed the Browse button on the bottom of the window. I navigated to the packages folder under the folder that my solution was in, then drilled down to the ...\mysolution\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40 and clicked on the Microsoft.Web.Infrastructure.dll. After clicking OK, the package showed up in my References list. I used the Web Deploy Package option to deploy my website and everything worked.
How about sed?
hour=`echo $hour|sed -e "s/^0*//g"`
I believe the simplest method would be to use Python:
python -m webbrowser "http://www.example.com/"
You can use the following format to generate a tooltip for an image.
<div class="tooltip"><img src="joe.jpg" />
<span class="tooltiptext">Tooltip text</span>
</div>
View the source of the login page. Look for the form
HTML tag. Within that tag is something that will look like action=
Use that value as $url
, not the URL of the form itself.
Also, while you are there, verify the input boxes are named what you have them listed as.
For example, a basic login form will look similar to:
<form method='post' action='postlogin.php'>
Email Address: <input type='text' name='email'>
Password: <input type='password' name='password'>
</form>
Using the above form as an example, change your value of $url
to:
$url="http://www.myremotesite.com/postlogin.php";
Verify the values you have listed in $postdata
:
$postdata = "email=".$username."&password=".$password;
and it should work just fine.
try this:
$('#foo').show(0).css('display','inline-block');
Use this, it may help.
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage("Do you want to exit app?")
.setNegativeButton("NO", null)
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
UserLogin.super.onBackPressed();
}
}).create().show();
}
You asked of Function but there is an easier way too. When you will upload the image, copy it's URL which is at the top right part of the window (View Screenshot) and paste it in the src='[link you copied]'
. Hope this will help if someone is looking for similar problem.
For all people ending here because of a codebase with a mix of Typegoose and Mongoose :
Create a db connection for each one :
Mongoose :
module.exports = db_mongoose.model("Car", CarSchema);
Typegoose :
db_typegoose.model("Car", CarModel.schema, "cars");
Yes, you can reference any image from the image
element. And you can use data URIs to make the SVG self-contained. An example:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
...
<image
width="100" height="100"
xlink:href="data:image/png;base64,IMAGE_DATA"
/>
...
</svg>
The svg
element attribute xmlns:xlink
declares xlink
as a namespace prefix and says where the definition is. That then allows the SVG reader to know what xlink:href
means.
The IMAGE_DATA
is where you'd add the image data as base64-encoded text. Vector graphics editors that support SVG usually have an option for saving with images embedded. Otherwise there are plenty of tools around for encoding a byte stream to and from base64.
Here's a full example from the SVG testsuite.
I always have to check my cheatsheet :-)
Step 1: right-click on the top of putty window and select 'Change settings'.
Step 2: type the name of the session and save.
That's it!. Enjoy!
I did not see this clearly articulated in any of the previous answers. Many programmers have no formal definition in mind when working with tables. We often communicate intuitively in terms of of "records" or "rows". However, with some exceptions for denormalized relations, tables are usually designed so that the relation between the non-key attributes and the key constitutes a set theoretic function.
A function can be defined as a subset of a cross-product between two sets, in which each element of the set of keys occurs at most once in the mapping. Hence the terminology arising from from that perspective tends to be singular. One sees the same singular (or at least, non-plural) convention across other mathematical and computational theories involving functions (algebra and lambda calculus for instance).
Forgive me - I couldn't resist ;-)
def goto(linenum):
global line
line = linenum
line = 1
while True:
if line == 1:
response = raw_input("yes or no? ")
if response == "yes":
goto(2)
elif response == "no":
goto(3)
else:
goto(100)
elif line == 2:
print "Thank you for the yes!"
goto(20)
elif line == 3:
print "Thank you for the no!"
goto(20)
elif line == 20:
break
elif line == 100:
print "You're annoying me - answer the question!"
goto(1)
Yes you can. Sometimes you may get asked this question that what is the purpose doing this? The answer is: sometimes we have to restrict the class from instantiating by its own. In that case, we want user to extend our Abstract class and instantiate child class
Try
try:
print undefined_var
except Exception as e:
print(e)
this will print the representation given by e.__str__()
:
"name 'undefined_var' is not defined"
you can also use:
print(repr(e))
which will include the Exception class name:
"NameError("name 'undefined_var' is not defined",)"
Yes you can use ALTER TABLE
as follows:
ALTER TABLE [table name] ALTER COLUMN [column name] [data type] NULL
Quoting from the ALTER TABLE
documentation:
NULL
can be specified inALTER COLUMN
to force aNOT NULL
column to allow null values, except for columns in PRIMARY KEY constraints.
You just need to a add the path of your PHP
file. In case you are using wamp
or have not installed it on the C drive.
Define the query method with signatures as follows.
@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
@Param("forename") String firstname);
}
For further details, check the Spring Data JPA reference
Many time this error is caused when you update a product in your custom module's observer as shown below.
class [NAMESPACE]_[MODULE NAME]_Model_Observer
{
/**
* Flag to stop observer executing more than once
*
* @var static bool
*/
static protected $_singletonFlag = false;
public function saveProductData(Varien_Event_Observer $observer)
{
if (!self::$_singletonFlag) {
self::$_singletonFlag = true;
$product = $observer->getEvent()->getProduct();
//do stuff to the $product object
// $product->save(); // commenting out this line prevents the error
$product->getResource()->save($product);
}
}
Hence whenever you save your product after updating some properties in your module's observer use $product->getResource()->save($product)
instead of $product->save()
On top of all the other stuff, for me this was happening because I was activating NewRelic in my setenv.sh:
NR_JAR=/opt/newrelic/newrelic.jar; export NR_JAR
Once I commented this, removing newrelic's hooks, the issue disappeared. It was only happening for endpoints using apache CXF.
You can have them both, just take off the "CURRENT_TIMESTAMP" flag on the created field. Whenever you create a new record in the table, just use "NOW()" for a value.
Or.
On the contrary, remove the 'ON UPDATE CURRENT_TIMESTAMP' flag and send the NOW() for that field. That way actually makes more sense.
In my experience I have found it's usually faster to run several queries, especially when retrieving large data sets.
When interacting with the database from another application, such as PHP, there is the argument of one trip to the server over many.
There are other ways to limit the number of trips made to the server and still run multiple queries that are often not only faster but also make the application easier to read - for example mysqli_multi_query.
I'm no novice when it comes to SQL, I think there is a tendency for developers, especially juniors to spend a lot of time trying to write very clever joins because they look smart, whereas there are actually smart ways to extract data that look simple.
The last paragraph was a personal opinion, but I hope this helps. I do agree with the others though who say you should benchmark. Neither approach is a silver bullet.
You can use Process.Start:
Dim url As String = “http://www.example.com“
Process.Start(url)
This should open whichever browser is set as default on the system.
I think it would be smart to only show the hand/pointer cursor when JavaScript is available. So people will not have the feeling they can click on something that is not clickable.
To achieve that you could use the JavaScript libary jQuery to add the CSS to the element like so
$("li").css({"cursor":"pointer"});
Or chain it directly to the click handler.
Or when modernizer in combination with <html class="no-js">
is used, the CSS would look like this:
.js li { cursor: pointer; }
There are 2 solutions for your problem:
mw.geometry('500x500')
OR
back.place(x = 0, y = 0, relwidth = 1, relheight = 1)
*The second option should be used in place of back.pack()
You properly written example should look like
void add_one(int& n) { n += 1; }
void add_one(int* const n)
{
if (n)
*n += 1;
}
That's why references are preferable if possible ...
If the charset of the tables is the same as it's content try to use mysql_set_charset('UTF8', $link_identifier)
. Note that MySQL uses UTF8
to specify the UTF-8 encoding instead of UTF-8
which is more common.
Check my other answer on a similar question too.
You can make it a non-submitting button (<button type="button">
) and hook something like window.location = 'http://where.you.want/to/go'
into its onclick handler. This does not work without javascript enabled though.
Or you can make it a submit button, and do a redirect on the server, although this obviously requires some kind of server-side logic, but the upside is that is doesn't require javascript.
(actually, forget the second solution - if you can't use a form, the submit button is out)
echo $date = date('H:i:s', strtotime('13:00:00 + 30 minutes') );
13:00:00 - any inputted time
30 minutes - any interval you wish (20 hours, 10 minutes, 1 seconds etc...)
If you use different version of play services libraries, you will get this error.
For example, below entries in build.gradle file cause the error as versions are different.
implementation 'com.google.android.gms:play-services-maps:11.4.2'
implementation 'com.google.android.gms:play-services-location:11.6.0'
To fix the issue use same versions.
implementation 'com.google.android.gms:play-services-maps:11.6.0'
implementation 'com.google.android.gms:play-services-location:11.6.0'
i got [ReflectionException] Class Seeder does not exist
too and when i use composer dump-autoload
, i got an error preg_match(): JIT compilation failed: no more memory
when i run it.
What i did is that i change ;pcre.jit=1
to pcre.jit=Off
in php.ini!
You can find the path by using php --ini
in your terminal!
I am using mac with php 7.3! Hope that help any of you guys out there!
Yet another advantage of .format
(which I don't see in the answers): it can take object properties.
In [12]: class A(object):
....: def __init__(self, x, y):
....: self.x = x
....: self.y = y
....:
In [13]: a = A(2,3)
In [14]: 'x is {0.x}, y is {0.y}'.format(a)
Out[14]: 'x is 2, y is 3'
Or, as a keyword argument:
In [15]: 'x is {a.x}, y is {a.y}'.format(a=a)
Out[15]: 'x is 2, y is 3'
This is not possible with %
as far as I can tell.
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
I see 2 options.
Using numpy:
property_a = numpy.array([545., 656., 5.4, 33.])
property_b = numpy.array([ 1.2, 1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]
Using a list comprehension and zip it:
property_a = [545., 656., 5.4, 33.]
property_b = [ 1.2, 1.3, 2.3, 0.3]
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = [x for x, y in zip(property_a, good_objects) if y]
property_bsel = [property_b[i] for i in good_indices]
You can try this if you are passing a value to the action method.
@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })
Remove the query string in case of no parameter passing.
Imagine a <span>
element inside a <div>
. If you give the <span>
element a height of 100px and a red border for example, it will look like this with
display: inline
display: inline-block
display: block
Code: http://jsfiddle.net/Mta2b/
Elements with display:inline-block
are like display:inline
elements, but they can have a width and a height. That means that you can use an inline-block element as a block while flowing it within text or other elements.
Difference of supported styles as summary:
margin-left
, margin-right
, padding-left
, padding-right
margin
, padding
, height
, width
We use the Url Rewrite extension for IIS for redirecting all HTTP requests to HTTPS. When trying to call a service not using transport security on an http://... address, this is the error that appeared.
So it might be worth checking if you can hit both the http and https addresses of the service via a browser and that it doesn't auto forward you with a 303 status code.
By specifying the @JoinColumn
on both models you don't have a two way relationship. You have two one way relationships, and a very confusing mapping of it at that. You're telling both models that they "own" the IDAIRLINE column. Really only one of them actually should! The 'normal' thing is to take the @JoinColumn
off of the @OneToMany
side entirely, and instead add mappedBy to the @OneToMany
.
@OneToMany(cascade = CascadeType.ALL, mappedBy="airline")
public Set<AirlineFlight> getAirlineFlights() {
return airlineFlights;
}
That tells Hibernate "Go look over on the bean property named 'airline' on the thing I have a collection of to find the configuration."
I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.
let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!
I did something close to that, the compiler is seeing that your return statement is in an If() statement. If you wish to resolve this error, simply create a new local variable called customerId before the If statement, then assign a value inside of the if statement. After the if statement, call your return statement, and return cstomerId. Like this:
Customer findCustomerByid(int id)
{
boolean exist=false;
if(this.customers.isEmpty()) {
return null;
}
for(int i=0;i<this.customers.size();i++) {
if(this.customers.get(i).getId() == id) {
exist=true;
break;
}
int customerId;
if(exist) {
customerId = this.customers.get(id);
} else {
customerId = this.customers.get(id);
}
}
return customerId;
}
You're in replace mode. Press the Insert
key on your keyboard to switch back to insert mode. Many applications that handle text have this in common.
If you have installed WAMP on your machine, please make sure that it is running. Do not EXIT the WAMP from tray menu since it will stop the MySQL Server.
I also needed what you've been searching for and did some research.
I found JSC3D (https://code.google.com/p/jsc3d/). It's a project written entirely in Javascript and uses the HTML canvas. It has been tested for Opera, Chrome, Firefox, Safari, IE9 and more.
Then you have services as p3d.in and Sketchfab that give you a nice reader to view 3D models on a web page: they use HTML5 and WebGL. They both have a free version.
To plot multiple graphs on the same figure you will have to do:
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, 'r') # plotting t, a separately
plt.plot(t, b, 'b') # plotting t, b separately
plt.plot(t, c, 'g') # plotting t, c separately
plt.show()
Turn the String into a char[], replace the letter by index, then convert the array back into a String.
String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);
for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.
Here are some up-to-date albeit narrow findings of mine with GCC 4.7.2 and Clang 3.2 for C++.
UPDATE: GCC 4.8.1 v clang 3.3 comparison appended below.
UPDATE: GCC 4.8.2 v clang 3.4 comparison is appended to that.
I maintain an OSS tool that is built for Linux with both GCC and Clang, and with Microsoft's compiler for Windows. The tool, coan, is a preprocessor and analyser of C/C++ source files and codelines of such: its computational profile majors on recursive-descent parsing and file-handling. The development branch (to which these results pertain) comprises at present around 11K LOC in about 90 files. It is coded, now, in C++ that is rich in polymorphism and templates and but is still mired in many patches by its not-so-distant past in hacked-together C. Move semantics are not expressly exploited. It is single-threaded. I have devoted no serious effort to optimizing it, while the "architecture" remains so largely ToDo.
I employed Clang prior to 3.2 only as an experimental compiler because, despite its superior compilation speed and diagnostics, its C++11 standard support lagged the contemporary GCC version in the respects exercised by coan. With 3.2, this gap has been closed.
My Linux test harness for current coan development processes roughly
70K sources files in a mixture of one-file parser test-cases, stress
tests consuming 1000s of files and scenario tests consuming < 1K files.
As well as reporting the test results, the harness accumulates and
displays the totals of files consumed and the run time consumed in coan
(it just passes each coan command line to the Linux time
command and
captures and adds up the reported numbers). The timings are flattered
by the fact that any number of tests which take 0 measurable time will
all add up to 0, but the contribution of such tests is negligible. The
timing stats are displayed at the end of make check
like this:
coan_test_timer: info: coan processed 70844 input_files.
coan_test_timer: info: run time in coan: 16.4 secs.
coan_test_timer: info: Average processing time per input file: 0.000231 secs.
I compared the test harness performance as between GCC 4.7.2 and Clang 3.2, all things being equal except the compilers. As of Clang 3.2, I no longer require any preprocessor differentiation between code tracts that GCC will compile and Clang alternatives. I built to the same C++ library (GCC's) in each case and ran all the comparisons consecutively in the same terminal session.
The default optimization level for my release build is -O2. I also successfully tested builds at -O3. I tested each configuration 3 times back-to-back and averaged the 3 outcomes, with the following results. The number in a data-cell is the average number of microseconds consumed by the coan executable to process each of the ~70K input files (read, parse and write output and diagnostics).
| -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 231 | 237 |0.97 |
----------|-----|-----|-----|
Clang-3.2 | 234 | 186 |1.25 |
----------|-----|-----|------
GCC/Clang |0.99 | 1.27|
Any particular application is very likely to have traits that play unfairly to a compiler's strengths or weaknesses. Rigorous benchmarking employs diverse applications. With that well in mind, the noteworthy features of these data are:
A further interesting comparison of the two compilers emerged by accident
shortly after those findings. Coan liberally employs smart pointers and
one such is heavily exercised in the file handling. This particular
smart-pointer type had been typedef'd in prior releases for the sake of
compiler-differentiation, to be an std::unique_ptr<X>
if the
configured compiler had sufficiently mature support for its usage as
that, and otherwise an std::shared_ptr<X>
. The bias to std::unique_ptr
was
foolish, since these pointers were in fact transferred around,
but std::unique_ptr
looked like the fitter option for replacing
std::auto_ptr
at a point when the C++11 variants were novel to me.
In the course of experimental builds to gauge Clang 3.2's continued need
for this and similar differentiation, I inadvertently built
std::shared_ptr<X>
when I had intended to build std::unique_ptr<X>
,
and was surprised to observe that the resulting executable, with default -O2
optimization, was the fastest I had seen, sometimes achieving 184
msecs. per input file. With this one change to the source code,
the corresponding results were these;
| -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.7.2 | 234 | 234 |1.00 |
----------|-----|-----|-----|
Clang-3.2 | 188 | 187 |1.00 |
----------|-----|-----|------
GCC/Clang |1.24 |1.25 |
The points of note here are:
Before and after the smart-pointer type change, Clang is able to build a
substantially faster coan executable at -O3 optimisation, and it can
build an equally faster executable at -O2 and -O3 when that
pointer-type is the best one - std::shared_ptr<X>
- for the job.
An obvious question that I am not competent to comment upon is why Clang should be able to find a 25% -O2 speed-up in my application when a heavily used smart-pointer-type is changed from unique to shared, while GCC is indifferent to the same change. Nor do I know whether I should cheer or boo the discovery that Clang's -O2 optimization harbours such huge sensitivity to the wisdom of my smart-pointer choices.
UPDATE: GCC 4.8.1 v clang 3.3
The corresponding results now are:
| -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.1 | 442 | 443 |1.00 |
----------|-----|-----|-----|
Clang-3.3 | 374 | 370 |1.01 |
----------|-----|-----|------
GCC/Clang |1.18 |1.20 |
The fact that all four executables now take a much greater average time than previously to process 1 file does not reflect on the latest compilers' performance. It is due to the fact that the later development branch of the test application has taken on lot of parsing sophistication in the meantime and pays for it in speed. Only the ratios are significant.
The points of note now are not arrestingly novel:
Comparing these results with those for GCC 4.7.2 and clang 3.2, it stands out that GCC has clawed back about a quarter of clang's lead at each optimization level. But since the test application has been heavily developed in the meantime one cannot confidently attribute this to a catch-up in GCC's code-generation. (This time, I have noted the application snapshot from which the timings were obtained and can use it again.)
UPDATE: GCC 4.8.2 v clang 3.4
I finished the update for GCC 4.8.1 v Clang 3.3 saying that I would stick to the same coan snaphot for further updates. But I decided instead to test on that snapshot (rev. 301) and on the latest development snapshot I have that passes its test suite (rev. 619). This gives the results a bit of longitude, and I had another motive:
My original posting noted that I had devoted no effort to optimizing coan for speed. This was still the case as of rev. 301. However, after I had built the timing apparatus into the coan test harness, every time I ran the test suite the performance impact of the latest changes stared me in the face. I saw that it was often surprisingly big and that the trend was more steeply negative than I felt to be merited by gains in functionality.
By rev. 308 the average processing time per input file in the test suite had well more than doubled since the first posting here. At that point I made a U-turn on my 10 year policy of not bothering about performance. In the intensive spate of revisions up to 619 performance was always a consideration and a large number of them went purely to rewriting key load-bearers on fundamentally faster lines (though without using any non-standard compiler features to do so). It would be interesting to see each compiler's reaction to this U-turn,
Here is the now familiar timings matrix for the latest two compilers' builds of rev.301:
coan - rev.301 results
| -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 428 | 428 |1.00 |
----------|-----|-----|-----|
Clang-3.4 | 390 | 365 |1.07 |
----------|-----|-----|------
GCC/Clang | 1.1 | 1.17|
The story here is only marginally changed from GCC-4.8.1 and Clang-3.3. GCC's showing
is a trifle better. Clang's is a trifle worse. Noise could well account for this.
Clang still comes out ahead by -O2
and -O3
margins that wouldn't matter in most
applications but would matter to quite a few.
And here is the matrix for rev. 619.
coan - rev.619 results
| -O2 | -O3 |O2/O3|
----------|-----|-----|-----|
GCC-4.8.2 | 210 | 208 |1.01 |
----------|-----|-----|-----|
Clang-3.4 | 252 | 250 |1.01 |
----------|-----|-----|------
GCC/Clang |0.83 | 0.83|
Taking the 301 and the 619 figures side by side, several points speak out.
I was aiming to write faster code, and both compilers emphatically vindicate my efforts. But:
GCC repays those efforts far more generously than Clang. At -O2
optimization Clang's 619 build is 46% faster than its 301 build: at -O3
Clang's
improvement is 31%. Good, but at each optimization level GCC's 619 build is
more than twice as fast as its 301.
GCC more than reverses Clang's former superiority. And at each optimization level GCC now beats Clang by 17%.
Clang's ability in the 301 build to get more leverage than GCC from -O3
optimization
is gone in the 619 build. Neither compiler gains meaningfully from -O3
.
I was sufficiently surprised by this reversal of fortunes that I suspected I might have accidentally made a sluggish build of clang 3.4 itself (since I built it from source). So I re-ran the 619 test with my distro's stock Clang 3.3. The results were practically the same as for 3.4.
So as regards reaction to the U-turn: On the numbers here, Clang has done much better than GCC at at wringing speed out of my C++ code when I was giving it no help. When I put my mind to helping, GCC did a much better job than Clang.
I don't elevate that observation into a principle, but I take the lesson that "Which compiler produces the better binaries?" is a question that, even if you specify the test suite to which the answer shall be relative, still is not a clear-cut matter of just timing the binaries.
Is your better binary the fastest binary, or is it the one that best compensates for cheaply crafted code? Or best compensates for expensively crafted code that prioritizes maintainability and reuse over speed? It depends on the nature and relative weights of your motives for producing the binary, and of the constraints under which you do so.
And in any case, if you deeply care about building "the best" binaries then you had better keep checking how successive iterations of compilers deliver on your idea of "the best" over successive iterations of your code.
git archive
also works with remote repository.
git archive --format=tar \
--remote=ssh://remote_server/remote_repository master | tar -xf -
To export particular path inside the repo add as many paths as you wish as last argument to git, e.g.:
git archive --format=tar \
--remote=ssh://remote_server/remote_repository master path1/ path2/ | tar -xv
I will try to explain it shortly.
First, you may notice that now you should use ConstraintLayout as requested by google (see androix library).
In your android studio projet, you can provide screen-specific layouts by creating additional res/layout/ directories. One for each screen configuration that requires a different layout.
This means you have to use the directory qualifier in both cases :
As a result, here is an exemple :
res/layout/main_activity.xml # For handsets
res/layout-land/main_activity.xml # For handsets in landscape
res/layout-sw600dp/main_activity.xml # For 7” tablets
res/layout-sw600dp-land/main_activity.xml # For 7” tablets in landscape
You can also use qualifier with res ressources files using dimens.xml.
res/values/dimens.xml # For handsets
res/values-land/dimens.xml # For handsets in landscape
res/values-sw600dp/dimens.xml # For 7” tablets
res/values/dimens.xml
<resources>
<dimen name="grid_view_item_height">70dp</dimen>
</resources>
res/values-land/dimens.xml
<resources>
<dimen name="grid_view_item_height">150dp</dimen>
</resources>
your_item_grid_or_list_layout.xml
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/constraintlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content
<ImageView
android:id="@+id/image"
android:layout_width="0dp"
android:layout_height="@dimen/grid_view_item_height"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="@drawable/border"
android:src="@drawable/ic_menu_slideshow">
</androidx.constraintlayout.widget.ConstraintLayout>
Source : https://developer.android.com/training/multiscreen/screensizes
Use Math.Max
:
int x = 3, y = 4, z = 5;
Console.WriteLine(Math.Max(Math.Max(x, y), z));
Send a POST request with content type = 'form-data':
import requests
files = {
'username': (None, 'myusername'),
'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)
You can use %
:
SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'
For SOA system architecture, I use the SOACP Visio stencil. It provides the symbols that are used in Thomas Erl's SOA book series.
I use the Visio Network and Database stencils to model most other requirements.
create table xyz_new as select * from xyz where 1=0;
http://www.codeassists.com/questions/oracle/copy-table-data-to-new-table-in-oracle
Try using Binding Values. You cannot use variables as you do in T-SQL but you can use "parameters". I hope the following link is usefull.Binding Values
You can use the title attribute, e.g. if you want to have a Tooltip over a text, just make:
<span title="This is a Tooltip">This is a text</span>
_x000D_
change to a another user and try except root. it works for me.
Right, click on the project. Go to Maven -> Update Project.
The dependencies will automatically be installed.
It's frustrating that what works great in one browser doesn't work in others. The following works in Firefox, but not in Chrome or IE:
<table width="80%">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody style="height:50px; overflow:auto">
<tr>
<td>Cell A1</td>
<td>Cell B1</td>
<td>Cell C1</td>
</tr>
<tr>
<td>Cell A2</td>
<td>Cell B2</td>
<td>Cell C2</td>
</tr>
<tr>
<td>Cell A3</td>
<td>Cell B3</td>
<td>Cell C3</td>
</tr>
</tbody>
</table>
The problem is that t.join() blocks the click event, the main thread does not get back to the event loop to process repaints. See Why ttk Progressbar appears after process in Tkinter or TTK progress bar blocked when sending email
Yes assuming you have this:
var WhatIsThe = AnswerToLife()
func AnswerToLife() int {
return 42
}
func init() {
WhatIsThe = 0
}
func main() {
if WhatIsThe == 0 {
fmt.Println("It's all a lie.")
}
}
AnswerToLife()
is guaranteed to run before init()
is called, and init()
is guaranteed to run before main()
is called.
Keep in mind that init()
is always called, regardless if there's main or not, so if you import a package that has an init
function, it will be executed.
Additionally, you can have multiple init()
functions per package; they will be executed in the order they show up in the file (after all variables are initialized of course). If they span multiple files, they will be executed in lexical file name order (as pointed out by @benc):
It seems that
init()
functions are executed in lexical file name order. The Go spec says "build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler". It seems thatgo build
works this way.
A lot of the internal Go packages use init()
to initialize tables and such, for example https://github.com/golang/go/blob/883bc6/src/compress/bzip2/bzip2.go#L480
building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x
using Newtonsoft.Json;
static class JsonObj
{
/// <summary>
/// Deserializes a json file into an object list
/// Author: Joseph Poirier 2/26/2019
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public static List<T> DeSerializeObject<T>(string fileName)
{
List<T> objectOut = new List<T>();
if (string.IsNullOrEmpty(fileName)) { return objectOut; }
try
{
// reading in full file as text
string ss = File.ReadAllText(fileName);
// went with <dynamic> over <T> or <List<T>> to avoid error..
// unexpected character at line 1 column 2
var output = JsonConvert.DeserializeObject<dynamic>(ss);
foreach (var Record in output)
{
foreach (T data in Record)
{
objectOut.Add(data);
}
}
}
catch (Exception ex)
{
//Log exception here
Console.Write(ex.Message);
}
return objectOut;
}
}
call to process
{
string fname = "../../Names.json"; // <- your json file path
// for alternate types replace string with custom class below
List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}
or this call to process
{
string fname = "../../Names.json"; // <- your json file path
// for alternate types replace string with custom class below
List<string> jsonFile = new List<string>();
jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}
Can be set via "Secure Text Entry" via Interface Builder
I think you could do it using a specs file.
Under MinGW you could run
gcc -dumpspecs > specs
Where it says
*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT}
You change it to
*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT} -std=c++11
And then place it in
/mingw/lib/gcc/mingw32/<version>/specs
I'm sure you could do the same without a MinGW build. Not sure where to place the specs file though.
The folder is probably either /gcc/lib/ or /gcc/.
Simply show a new window with two buttons. Add property to contain user result.
Use the basename
method of the path
module:
var path = require('path');
var filename = path.basename(__filename);
console.log(filename);
Here is the documentation the above example is taken from.
As Dan pointed out, Node is working on ECMAScript modules with the "--experimental-modules" flag. Node 12 still supports __dirname
and __filename
as above.
If you are using the --experimental-modules
flag, there is an alternative approach.
The alternative is to get the path to the current ES module:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
If you have a function:
$function:foo | % Invoke @(
'bar'
'directory'
$true
)
If you have a cmdlet:
[PSCustomObject] @{
Path = 'bar'
Type = 'directory'
Force = $true
} | New-Item
If you have an application:
{foo.exe @Args} | % Invoke @(
'bar'
'directory'
$true
)
Or
icm {foo.exe @Args} -Args @(
'bar'
'directory'
$true
)
If you set the margin to be margin:0 auto
the image will be centered.
This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.
I found this, hope it helps http://www.zackgrossbart.com/hackito/touchslider/
If you have two DateTime that looks the same, but Compare or Equals doesn't return what you expect, this is how to compare them.
Here an example with 1-millisecond precision:
bool areSame = (date1 - date2) > TimeSpan.FromMilliseconds(1d);
.ToList returns an empty list. (same as new List() );