You can use relative path to mount the volume to container:
docker run -v `pwd`/certs:/container/path/to/certs ...
Note the back tick on the pwd
which give you the present working directory. It assumes you have the certs
folder in current directory that the docker run
is executed. Kinda great for local development and keep the certs folder visible to your project.
Get list of all the tables and the fields in database:
Select *
From INFORMATION_SCHEMA.COLUMNS
Where TABLE_CATALOG Like 'DatabaseName'
Get list of all the fields in table:
Select *
From INFORMATION_SCHEMA.COLUMNS
Where TABLE_CATALOG Like 'DatabaseName' And TABLE_NAME Like 'TableName'
Microsoft started to address the issue in late 2015 by releasing VisualStudioUninstaller.
They abandoned the solution for a while; however work has begun again as of April 2016.
There has finally been an official release for this uninstaller in April 2016 which is described as being "designed to cleanup/scorch all Preview/RC/RTM releases of Visual Studio 2013, Visual Studio 2015 and Visual Studio vNext".
One-liner.
i.fa.fa-chevron-right.collapse.in { transform: rotate(180deg); }
In this example it's being used to group collapsible table rows. The only thing you need to do is add the target class name (my-collapse-name) to your icon:
<tr data-toggle="collapse" data-target=".my-collapse-name">
<th><i class="fa fa-chevron-right my-collapse-name"></span></th>
<th>Master Row - Title</th>
</tr>
<tr class="collapse my-collapse-name">
<td></td>
<td>Detail Row - Content</td>
</tr>
You could accomplish the same with Bootstrap's native caret class by using <span class='caret my-collapse-name'></span>
and span.caret.collapse.in { transform: rotate(90deg); }
Based on Guffa's answer, in an extension class, use:
public static string[] Lines(this string source) {
return source.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
}
Try this demo please: http://jsfiddle.net/sgpw2/
Thanks Jan for spaces \s
rest there is some good detail in this link:
http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UHKS5UIihlI
Hope it fits your need :)
code
$(function() {
$("#field").bind("keyup", function(event) {
var regex = /^[a-zA-Z\s]+$/;
if (regex.test($("#field").val())) {
$('.validation').html('valid');
} else {
$('.validation').html("FAIL regex");
}
});
});?
I had this problem and I was able to fix this by updating npm
sudo npm update -g npm
Before the update, the result of npm info graceful-fs | grep 'version:'
was:
version: '3.3.12'
After the update the result is:
version: '3.9.3'
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
Go to the project explorer block ... right click on project name select "Build Path"-----------> "Configuration Build Path"
then the pop up window will get open.
in this pop up window you will find 4 tabs. 1)source 2) project 3)Library 4)order and export
Click on 1) Source
select the project (under which that file is present which you want to compile)
and then click on ok....
Go to the workspace location of the project open a bin folder and search that class file ...
you will get that java file compiled...
just to cross verify check the changed timing.
hope this will help.
Thanks.
Try this:
var res = list.ToDictionary(x => x, x => x);
The first lambda lets you pick the key, the second one picks the value.
You can play with it and make values differ from the keys, like this:
var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));
If your list contains duplicates, add Distinct()
like this:
var res = list.Distinct().ToDictionary(x => x, x => x);
EDIT To comment on the valid reason, I think the only reason that could be valid for conversions like this is that at some point the keys and the values in the resultant dictionary are going to diverge. For example, you would do an initial conversion, and then replace some of the values with something else. If the keys and the values are always going to be the same, HashSet<String>
would provide a much better fit for your situation:
var res = new HashSet<string>(list);
if (res.Contains("string1")) ...
The approach with the most upvotes (from John Doe) does somehow work for me but in my case from expected 422 rows i get only 180. I couldn't find anything wrong and there are no errors at all, so i looked for a different simple approach.
Using IF NOT FOUND THEN
after a SELECT
just works perfectly for me.
(described in PostgreSQL Documentation)
Example from documentation:
SELECT * INTO myrec FROM emp WHERE empname = myname;
IF NOT FOUND THEN
RAISE EXCEPTION 'employee % not found', myname;
END IF;
Syntex for latest MySQL versions has been changed.
So try RENAME command without SINGLE QUOTES in table names.
RENAME TABLE old_name_of_table TO new_name_of_table;
A naming service associates names with objects and finds objects based on their given names.(RMI registry is a good example of a naming service.) JNDI provides a common interface to many existing naming services, such as LDAP, DNS.
Without JNDI, the location or access information of remote resources would have to be hard-coded in applications or made available in a configuration. Maintaining this information is quite tedious and error prone.
gene_name = no_headers.iloc[1:,[1]]
This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:
gene_name[x]
you now have a Series object with a single value. You can't hash the Series.
The solution is to create Series from the start.
gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]
Also, where you have orph_dict[gene_name[x]] =+ 1
, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1
to increment the counter.
Steps: 1. Open a command prompt with administrator's rights.
Steps: 2. Run the command: setx /M PATH "path\to;%PATH%"
[Note: Be sure to alter the command so that path\to reflects the folder path from your root.]
Example : setx /M PATH "C:\Program Files;%PATH%"
@Esteban Küber is absolutely right.
Maybe one additional hint for bloody beginners like me. If you speciify the variables with %s, you have to follow this principle for EVERY input value, which means for the SET-variables as well as for the WHERE-variables.
Otherwise, you will have to face a termination message like 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s WHERE'
The problem might be with your firewall or antivirus.
Make sure they all disabled.
Run your script in Eclipse. If it works, then 2 and 3 might be the culprit. For me, it was comodo firewall. I created a filter for Adb.exe
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
Another option would be to just use perl with globstar.
Enabling shopt -s globstar
in your .bashrc
(or wherever) allows the **
glob pattern to match all sub-directories and files recursively.
Thus using perl -pXe 's/SEARCH/REPLACE/g' -i **
will recursively
replace SEARCH
with REPLACE
.
The -X
flag tells perl to "disable all warnings" - which means that
it won't complain about directories.
The globstar also allows you to do things like sed -i 's/SEARCH/REPLACE/g' **/*.ext
if you wanted to replace SEARCH
with REPLACE
in all child files with the extension .ext
.
you can also use OPEN Sql to find the number of rows using the COUNT Grouping clause and also there is system field SY-LINCT to count the lines(ROWS) of your table.
I encountered this issue on a WordPress site. The headers on dropdown menus always had the attribute href=""
and the header plugin being used only allowed standard urls. The easiest solution there was just to run this code in the footer:
jQuery('[href=""]').click(function(e){
e.preventDefault();
});
This will prevent blank anchors from doing anything.
Counting lines is too tedious for me, but counting 'paragraphs' isn't so bad. '{' and '}' move the cursor to the first empty line before and after the cursor, respectively. Cursor moving operations can be combined with deletion, and several other answers used a similar approach (dd for a line, dG for the end of the document, etc.)
For example:
/* Lorem ipsum dolor sit amet, consectetur adipiscing elit. */
Lorem *ipsum(void) {
return dolor(sit, amet);
}
If your cursor starts above the comment block, 'd}' deletes the comment block, and 'd2}' deletes both the comment block and the code block. If your cursor starts below the code block, 'd{' deletes the code, and 'd2{' deletes both. Of course, you can skip over one block by moving the cursor first: '{d{' or '}d}'.
If you're consistent with your whitespace, or you can count the paragraphs at a glance, this should work. The Vim help file has more cursor tricks if you're interested.
using System;
using System.Collections.Generic;
class MainApp
{
static void Main()
{
LoadBalancer oldbalancer = null;
for (int i = 0; i < 15; i++)
{
LoadBalancer balancerNew = LoadBalancer.GetLoadBalancer();
if (oldbalancer == balancerNew && oldbalancer != null)
{
Console.WriteLine("{0} SameInstance {1}", oldbalancer.Server, balancerNew.Server);
}
oldbalancer = balancerNew;
}
Console.ReadKey();
}
}
class LoadBalancer
{
private static LoadBalancer _instance;
private List<string> _servers = new List<string>();
private Random _random = new Random();
private static object syncLock = new object();
private LoadBalancer()
{
_servers.Add("ServerI");
_servers.Add("ServerII");
_servers.Add("ServerIII");
_servers.Add("ServerIV");
_servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
{
_instance = new LoadBalancer();
}
}
}
return _instance;
}
public string Server
{
get
{
int r = _random.Next(_servers.Count);
return _servers[r].ToString();
}
}
}
I took code from dofactory.com, nothing so fancy but I find this far good than examples with Foo and Bar additionally book from Judith Bishop on C# 3.0 Design Patterns has example about active application in mac dock.
If you look at code we are actually building new objects on for loop, so that creates new object but reuses instance as a result of which the oldbalancer and newbalancer has same instance, How? its due to static keyword used on function GetLoadBalancer(), despite of having different server value which is random list, static on GetLoadBalancer() belongs to the type itself rather than to a specific object.
Additionally there is double check locking here
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
since from MSDN
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
so every-time mutual-exclusion lock is issued, even if it don't need to which is unnecessary so we have null check.
Hopefully it helps in clearing more.
And please comment if I my understanding is directing wrong ways.
Try like this...
Update t1.Column1 = value
from tbltemp as t1
inner join tblUser as t2 on t2.ID = t1.UserID
where t1.[column1]=value and t2.[Column1] = value;
This can be also thought of as a simple map reduce operation if you would like to think of it from a functional programming perspective.
import os
folders = [("home",".vim"),("home","zathura")]
[reduce(lambda x,y: os.path.join(x,y), each, "") for each in folders]
reduce
is builtin in Python 2.x. In Python 3.x it has been moved to itertools
However the accepted the answer is better.
This has been answered below but answering if you have a list of items that needs to be joined.
This is possible with <textarea>
the only thing you need to do is use
Summernote WYSIWYG editor
it interprets HTML tags inside a textarea (namely <strong>
, <i>
, <u>
, <a>
)
There is a mySQL bug report from 2004 that still seems to have some validity. It seems that in 4.x, this was fastest:
DROP table_name
CREATE TABLE table_name
TRUNCATE table_name
was DELETE FROM
internally back then, providing no performance gain.
This seems to have changed, but only in 5.0.3 and younger. From the bug report:
[11 Jan 2005 16:10] Marko Mäkelä
I've now implemented fast TRUNCATE TABLE, which will hopefully be included in MySQL 5.0.3.
A tool is a big help.
However, there are times when you can't use a tool: the heap dump is so huge it crashes the tool, you are trying to troubleshoot a machine in some production environment to which you only have shell access, etc.
In that case, it helps to know your way around the hprof dump file.
Look for SITES BEGIN. This shows you what objects are using the most memory. But the objects aren't lumped together solely by type: each entry also includes a "trace" ID. You can then search for that "TRACE nnnn" to see the top few frames of the stack where the object was allocated. Often, once I see where the object is allocated, I find a bug and I'm done. Also, note that you can control how many frames are recorded in the stack with the options to -Xrunhprof.
If you check out the allocation site, and don't see anything wrong, you have to start backward chaining from some of those live objects to root objects, to find the unexpected reference chain. This is where a tool really helps, but you can do the same thing by hand (well, with grep). There is not just one root object (i.e., object not subject to garbage collection). Threads, classes, and stack frames act as root objects, and anything they reference strongly is not collectible.
To do the chaining, look in the HEAP DUMP section for entries with the bad trace id. This will take you to an OBJ or ARR entry, which shows a unique object identifier in hexadecimal. Search for all occurrences of that id to find who's got a strong reference to the object. Follow each of those paths backward as they branch until you figure out where the leak is. See why a tool is so handy?
Static members are a repeat offender for memory leaks. In fact, even without a tool, it'd be worth spending a few minutes looking through your code for static Map members. Can a map grow large? Does anything ever clean up its entries?
I would recommend checking out Otto, an EventBus tailored specifically to Android. Your Activity/UI can listen to events posted on the Bus from the Service, and decouple itself from the backend.
This's my take on this, it's in Kotlin but can be converted to Java with little effort:
val percentageRegex = Regex("""(?<!\\)%""")
val underscoreRegex = Regex("""(?<!\\)_""")
infix fun String.like(predicate: String): Boolean {
//Split the text by every % not preceded by a slash.
//We transform each slice before joining them with .* as a separator.
return predicate.split(percentageRegex).joinToString(".*") { percentageSlice ->
//Split the text by every _ not preceded by a slash.
//We transform each slice before joining them with . as a separator.
percentageSlice.split(underscoreRegex).joinToString(".") { underscoreSlice ->
//Each slice is wrapped in "Regex quotes" to ignore all
// the metacharacters they contain.
//We also remove the slashes from the escape sequences
// since they are now treated literally.
Pattern.quote(
underscoreSlice.replace("\\_", "_").replace("\\%", "%")
)
}
}.let { "^$it$" }.toRegex().matches(this@like)
}
It might not be the most performant of all the solutions here, but it's probably the most accurate.
It ignores all the other Regex metacharacters other than % and _ and also supports escaping them with a slash.
Just add all fields to the query and remember to add them to Group By as well.
Select shoppername, a, b, amountpayed, item, count(*) as cnt
from dbo.sales
group by shoppername, a, b, amountpayed, item
having count(*) > 1
Even I have experience some more strange things, I can see there is no dll in GAC from where the dll is loading but windows > Module shows system.dll version=4.0.0.0 loaded
On Version 1.9.6.1. For UnPushed commit.
Use below date function to get current time in MySQL format/(As requested on question also)
echo date("Y-m-d H:i:s", time());
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
you can try with
document.getElementById('btn').disabled = !this.checked"
<input type="submit" name="btn" id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox" onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
I just cleared the profiles with the Apple Configurator, restarted the iDevice and worked again as usual.
When the button is clicked, get the value of the input and use it to create an image element which is appended to the body (or anywhere else) :
<html>
<body>
<form>
<input type="text" id="imagename" value="" />
<input type="button" id="btn" value="GO" />
</form>
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
var val = document.getElementById('imagename').value,
src = 'http://webpage.com/images/' + val +'.png',
img = document.createElement('img');
img.src = src;
document.body.appendChild(img);
}
</script>
</body>
</html>
the same in jQuery:
$('#btn').on('click', function() {
var img = $('<img />', {src : 'http://webpage.com/images/' + $('#imagename').val() +'.png'});
img.appendTo('body');
});
I've found some useful hacks on this:
Using JS how can I stop child Iframes from redirecting or at least prompt users about the redirect
http://www.codinghorror.com/blog/2009/06/we-done-been-framed.html
http://coderrr.wordpress.com/2009/02/13/preventing-frame-busting-and-click-jacking-ui-redressing/
shallow
var obj = { name : "Jacob" , address : ["America"] }
var obj2 = { name : "Shaun" , address : ["Honk Kong"] }
var merged = Object.assign({} , obj,obj2 ); //shallow merge
obj2.address[0] = "new city"
result.address[0] is changed to "new city" , i.e merged object is also changed. This is the problem with shallow merge.
deep
var obj = { name : "Jacob" , address : ["America"] }
var obj2 = { name : "Shaun" , address : ["Honk Kong"] }
var result = Object.assign({} , JSON.parse(JSON.stringify(obj)),JSON.parse(JSON.stringify(obj2)) )
obj2.address[0] = "new city"
result.address[0] is not changed
To build upon @6twenty's answer...I prefer panTo(LatLng) over setCenter(LatLng) as panTo animates for smoother transition to center "if the change is less than both the width and height of the map". https://developers.google.com/maps/documentation/javascript/reference#Map
The below uses Google Maps API v3.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
title: markerTitle,
map: map,
});
google.maps.event.addListener(marker, 'click', function () {
map.panTo(marker.getPosition());
//map.setCenter(marker.getPosition()); // sets center without animation
});
Here is how to get rid of the top section header in a grouped UITableView, in Swift:
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
In regards to the answer provided by Fuzzy:
I actually had to do something slightly different.
Project -> Properties -> C/C++ Build -> Settings -> GCC C Linker -> Libraries
Click the little green add icon, type m and hit ok. Everything in this window automatically has -l applied to it since it is a library.
Not as complicated as it sounds.... Just leave the duplicate primary key out of your query.... this works for me !
INSERT INTO
Content(
`status`,
content_category,
content_type,
content_id,
user_id,
title,
description,
content_file,
content_url,
tags,
create_date,
edit_date,
runs
)
SELECT `status`,
content_category,
content_type,
content_id,
user_id,
title,
description,
content_file,
content_url,
tags,
create_date,
edit_date,
runs
FROM
Content_Images
As seeing here answered by Chen Houwu, it's possible to use string package:
import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
This type of operation is exactly what aggregate
was designed for:
d <- read.table(text=
'Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32', header=TRUE)
aggregate(d[, 3:4], list(d$Name), mean)
Group.1 Rate1 Rate2
1 Aira 16.33333 47.00000
2 Ben 31.33333 50.33333
3 Cat 44.66667 54.00000
Here we aggregate columns 3 and 4 of data.frame d
, grouping by d$Name
, and applying the mean
function.
Or, using a formula interface:
aggregate(. ~ Name, d[-2], mean)
To remove all files from a directory, first you need to list all files in the directory using fs.readdir
, then you can use fs.unlink
to remove each file. Also fs.readdir
will give just the file names, you need to concat with the directory name to get the full path.
Here is an example
const fs = require('fs');
const path = require('path');
const directory = 'test';
fs.readdir(directory, (err, files) => {
if (err) throw err;
for (const file of files) {
fs.unlink(path.join(directory, file), err => {
if (err) throw err;
});
}
});
There is a recursive
flag that you can use in rmdir
to remove all the files recursively. See nodejs docs for more information.
const fs = require('fs').promises;
const directory = 'test';
fs.rmdir(directory, { recursive: true })
.then(() => console.log('directory removed!'));
There begin to appear some answers that assume you want to get all <td>
elements from #table
. If so, the simplest cross-browser way how to do this is document.getElementById('table').getElementsByTagName('td')
. This works because getElementsByTagName
doesn't return only immediate children. No loops are needed.
Don't reinvent the wheel, use this package v-click-outside
The first answer is too complex, historic, and uninformative for my tastes.
It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,
Let's start with the first. Very often with something like Debian you'll see.
RUN apt-get update \
&& apt-get dist-upgrade \
&& apt-get install <whatever> \
&& apt-get clean
We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,
RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;
It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean
doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree
for an example of that).
By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from
syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean
), and you would otherwise have lots of un-needed files in your final image.
See also
Here are some dplyr
options:
# sample data
df <- data.frame(a = c('1', NA, '3', NA), b = c('a', 'b', 'c', NA), c = c('e', 'f', 'g', NA))
library(dplyr)
# remove rows where all values are NA:
df %>% filter_all(any_vars(!is.na(.)))
df %>% filter_all(any_vars(complete.cases(.)))
# remove rows where only some values are NA:
df %>% filter_all(all_vars(!is.na(.)))
df %>% filter_all(all_vars(complete.cases(.)))
# or more succinctly:
df %>% filter(complete.cases(.))
df %>% na.omit
# dplyr and tidyr:
library(tidyr)
df %>% drop_na
The way I build CMake projects cross platform is the following:
/project-root> mkdir build
/project-root> cd build
/project-root/build> cmake -G "<generator>" -DCMAKE_INSTALL_PREFIX=stage ..
/project-root/build> cmake --build . --target=install --config=Release
./project-root/build/stage
- the path is always considered relative to the current directory if it is not absolute).
with the buildsystem configured in the line before. It will execute the install
target which also builds all necessary dependent targets if they need to be built and then copies the files into the CMAKE_INSTALL_PREFIX
(which in this case is ./project-root/build/stage
. For multi-configuration builds, like in Visual Studio, you can also specify the configuration with the optional --config <config>
flag.cmake --build
command is that it works for all generators (i.e. makefiles and Visual Studio) without needing different commands.Afterwards I use the installed files to create packages or include them in other projects...
Finaly I found another answer for this problem. and this is working for me. Just add below datas to the your webconfig file.
<configuration>
<system.webServer>
<security>
<requestFiltering>
<verbs allowUnlisted="true">
<add verb="OPTIONS" allowed="false" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Form more information, you can visit this web site: http://www.iis.net/learn/manage/configuring-security/use-request-filtering
if you want to test your web site, is it working or not... You can use "HttpRequester" mozilla firefox plugin. for this plugin: https://addons.mozilla.org/En-us/firefox/addon/httprequester/
static void Main()
{
// A.
// Example strings with multiple whitespaces.
string s1 = "He saw a cute\tdog.";
string s2 = "There\n\twas another sentence.";
// B.
// Create the Regex.
Regex r = new Regex(@"\s+");
// C.
// Strip multiple spaces.
string s3 = r.Replace(s1, @" ");
Console.WriteLine(s3);
// D.
// Strip multiple spaces.
string s4 = r.Replace(s2, @" ");
Console.WriteLine(s4);
Console.ReadLine();
}
OUTPUT:
He saw a cute dog. There was another sentence. He saw a cute dog.
I just ran into this issue today and am pretty sure I solved it by doing:
git branch temp
git checkout master
git merge temp
I was on my work computer when I figured out how to do this, and now I'm running into the same problem on my personal computer. So will have to wait till Monday when I'm back at the work computer to see exactly how I did it.
Edit: The original link I answered with is now invalid.The newer URL would be https://developers.google.com/web/tools/chrome-devtools/javascript/add-breakpoints#exceptions as of 2016-11-11.
I realize this question has an answer, but it's no longer accurate. Use the link above ^
(link replaced by edited above) - you can now set it to break on all exceptions or just unhandled ones. (Note that you need to be in the Sources tab to see the button.)
Chrome's also added some other really useful breakpoint capabilities now, such as breaking on DOM changes or network events.
Normally I wouldn't re-answer a question, but I had the same question myself, and I found this now-wrong answer, so I figured I'd put this information in here for people who came along later in searching. :)
Format 1 : $format1 = "2012-12-31";
Format 2 : $format2 = "31-12-2012";
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$format1)) {
return true;
} else {
return false;
}
if (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-[0-9]{4}$/",$format2)) {
return true;
} else {
return false;
}
Below is the code that works with both the email or messaging app. If you share through email then the subject and body both are added.
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareString = Html.fromHtml("Medicine Name:" + medicine_name +
"<p>Store Name:" + “store_name “+ "</p>" +
"<p>Store Address:" + “store_address” + "</p>") .toString();
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Medicine Enquiry");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareString);
if (sharingIntent.resolveActivity(context.getPackageManager()) != null)
context.startActivity(Intent.createChooser(sharingIntent, "Share using"));
else {
Toast.makeText(context, "No app found on your phone which can perform this action", Toast.LENGTH_SHORT).show();
}
Cascade will work when you delete something on table Courses
. Any record on table BookCourses
that has reference to table Courses
will be deleted automatically.
But when you try to delete on table BookCourses
only the table itself is affected and not on the Courses
follow-up question: why do you have CourseID
on table Category?
Maybe you should restructure your schema into this,
CREATE TABLE Categories
(
Code CHAR(4) NOT NULL PRIMARY KEY,
CategoryName VARCHAR(63) NOT NULL UNIQUE
);
CREATE TABLE Courses
(
CourseID INT NOT NULL PRIMARY KEY,
BookID INT NOT NULL,
CatCode CHAR(4) NOT NULL,
CourseNum CHAR(3) NOT NULL,
CourseSec CHAR(1) NOT NULL,
);
ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;
Keep in mind if you are wanting to test this component you will want to inject the window. Use the @Inject() function to inject the window object by naming it using a string token like detailed in this duplicate
The simplest way: run git push -u origin feature/123-sandbox-tests
once. That pushes the branch the way you're used to doing it and also sets the upstream tracking info in your local config. After that, you can just git push
to push tracked branches to their upstream remote(s).
You can also do this in the config yourself by setting branch.<branch name>.merge
to the remote branch name (in your case the same as the local name) and optionally, branch.<branch name>.remote
to the name of the remote you want to push to (defaults to origin). If you look in your config, there's most likely already one of these set for master
, so you can follow that example.
Finally, make sure you consider the push.default
setting. It defaults to "matching", which can have undesired and unexpected results. Most people I know find "upstream" more intuitive, which pushes only the current branch.
Details on each of these settings can be found in the git-config man page.
On second thought, on re-reading your question, I think you know all this. I think what you're actually looking for doesn't exist. How about a bash function something like (untested):
function pushCurrent {
git config push.default upstream
git push
git config push.default matching
}
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
See my article. I had the same problem - LazyInitializationException - and here's the answer I finally came up with:
http://community.jboss.org/wiki/LazyInitializationExceptionovercome
Setting lazy=false is not the answer - it can load everything all at once, and that's not necessarily good. Example:
1 record table A references:
5 records table B references:
25 records table C references:
125 records table D
...
etc. This is but one example of what can go wrong.
--Tim Sabin
The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.
The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc). ......
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hyphen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
This works like a clock for me:
methods: {
hasHistory () { return window.history.length > 2 }
}
Then, in the template:
<button
type="button"
@click="hasHistory()
? $router.go(-1)
: $router.push('/')" class="my-5 btn btn-outline-success">«
Back
</button>
There's a relatively new service called HockeyApp, which seems to rival TestFlight, however they claim to give you access to unlimited users, but it does cost some $$ unlike TestFlight which has now been integrated directly into iTunes Connect.
Here is a great way to build dynamic fields for a pivot query:
--summarize values to a tmp table
declare @STR varchar(1000)
SELECT @STr = COALESCE(@STr +', ', '')
+ QUOTENAME(DateRange)
from (select distinct DateRange, ID from ##pivot)d order by ID
---see the fields generated
print @STr
exec(' .... pivot code ...
pivot (avg(SalesAmt) for DateRange IN (' + @Str +')) AS P
order by Decile')
Use button.layer.cornerRadius
, button.layer.borderColor
and button.layer.borderWidth
.
Note that borderColor
requires a CGColor
, so you could say (Swift 3/4):
button.backgroundColor = .clear
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor
Instead of if-else condition use if in both conditions. it will work that way but not sure why.
I just posted an answer to a question that was subequently closed as a duplicate of this one (for good reasons I think), but I'm surprised to see that my proposed solution is not included in any of the answers here.
Rather than using a defaultdict
or messing around with membership tests or manual exception handling, you can easily append values onto lists within a dictionary using the setdefault
method:
results = {} # use a normal dictionary for our output
for k, v in some_data: # the keys may be duplicates
results.setdefault(k, []).append(v) # magic happens here!
This is a lot like using a defaultdict, but you don't need a special data type. When you call setdefault
, it checks to see if the first argument (the key) is already in the dictionary. If doesn't find anything, it assigns the second argument (the default value, an empty list in this case) as a new value for the key. If the key does exist, nothing special is done (the default goes unused). In either case though, the value (whether old or new) gets returned, so we can unconditionally call append
on it, knowing it should always be a list.
here is a best way to disable cut copy paste of editText work in all version
if (android.os.Build.VERSION.SDK_INT < 11) {
editText.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
menu.clear();
}
});
} else {
editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
public boolean onActionItemClicked(ActionMode mode,
MenuItem item) {
// TODO Auto-generated method stub
return false;
}
});
}
After reading the other answers, I still had trouble understanding why the set comes out un-ordered.
Mentioned this to my partner and he came up with this metaphor: take marbles. You put them in a tube a tad wider than marble width : you have a list. A set, however, is a bag. Even though you feed the marbles one-by-one into the bag; when you pour them from a bag back into the tube, they will not be in the same order (because they got all mixed up in a bag).
That should help
df.groupby(['NFF', 'ABUSE']).size().unstack().plot(kind='bar', stacked=True)
You can do this with JQueryUI:
$('a').mouseenter(function(){
$(this).animate({
color: '#ff0000'
}, 1000);
}).mouseout(function(){
$(this).animate({
color: '#000000'
}, 1000);
});
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime
method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime
module also named their class datetime
:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
specifically I want to overload
Boolean.Parse
to allow an int argument.
Would an extension for int work?
public static bool ToBoolean(this int source){
// do it
// return it
}
Then you can call it like this:
int x = 1;
bool y = x.ToBoolean();
You cannot have two TIMESTAMP column with the same default value of CURRENT_TIMESTAMP on your table. Please refer to this link: http://www.mysqltutorial.org/mysql-timestamp.aspx
Postback refers to HTML forms. An HTML form has 2 methods: GET and POST. These methods determine how data is sent from the client via the form, to the server. A Postback is the action of POSTing back to the submitting page. In essence, it forms a complete circuit from the client, to the server, and back again.
Try this:
window.onmousewheel = document.onmousewheel = null
window.ontouchmove = null
window.onwheel = null
If you want to convert a single VARBINARY
value into VARCHAR
(STRING
) you can do by declaring a variable like this:
DECLARE @var VARBINARY(MAX)
SET @var = 0x21232F297A57A5A743894A0E4A801FC3
SELECT CAST(@var AS VARCHAR(MAX))
If you are trying to select from table column then you can do like this:
SELECT CAST(myBinaryCol AS VARCHAR(MAX))
FROM myTable
Here's the solution,
If you are a constant proxy changer like me for various reasons (university, home , workplace and so on..) you are mostly likely to get this error due to improper configuration of connection settings in the eclipse IDE. all you have to do it play around with the current settings and get it to working state. Here's how,,
1. GO TO
Window-> Preferences -> General -> Network Connection.
2. Change the Settings
Active Provider-> Manual-> and check---> HTTP, HTTPS and SOCKS
If your active provider is already set to Manual, try restoring the default (native)
That's all, restart Eclipse and you are good to go!
setTimeout
is a kind of Thread, it holds a operation for a given time and execute.
setTimeout(function,time_in_mills);
in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.
setTimeout(function(){console.log('your name')},3000);
Key point to remember is, what ever you want to do by using the setTimeout
method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:
setTimeout(function(){yourOtherMethod(parameter);},3000);
For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:
import javax.mail.*
import javax.mail.internet.*
private class SMTPAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication('[email protected]', 'test1234');
}
}
def d_email = "[email protected]",
d_uname = "email",
d_password = "password",
d_host = "smtp.gmail.com",
d_port = "465", //465,587
m_to = "[email protected]",
m_subject = "Testing",
m_text = "Hey, this is the testing email."
def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")
def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);
def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))
Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
ok so I used this:
public partial class Form1 : Form
{
private void Button_Click(object sender, EventArgs e)
{
Form2 myForm = new Form2();
this.Hide();
myForm.ShowDialog();
this.Close();
}
}
This seems to be working fine but the first form is just hidden and it can still generate events. the "this.Close()" is needed to close the first form but if you still want your form to run (and not act like a launcher) you MUST replace it with
this.Show();
Best of luck!
"Day of Week" is actually something you can get directly from the php date() function with the format "l" or "N" respectively. Have a look at the manual
edit: Sorry I didn't read the posts of Kalium properly, he already explained that. My bad.
One more option - mod_qos
Not simple to configure - but powerful.
This is not right. Here's how you should use Runtime.exec()
. You might also try its more modern cousin, ProcessBuilder
:
I have looked through many loggers, and I wasn't able to find a lightweight solution - so I decided to make a simple solution that is posted on github.
I hope this helps you out.
http://bluejamesbond.github.io/Scribe.js/
Another solution to navigate through JSON documents is JSONiq (implemented in the Zorba engine), where you can write something like:
jsoniq version "1.0";
let $doc := [
{"id":"10", "class": "child-of-9"},
{"id":"11", "class": "child-of-10"}
]
for $entry in members($doc) (: binds $entry to each object in turn :)
return $entry.class (: gets the value associated with "class" :)
You can run it on http://try.zorba.io/
If you want to download gradle with source and docs, the default distribution url configured in gradle-wrapper.properites will not satisfy your need.It is https://services.gradle.org/distributions/gradle-2.10-bin.zip, not https://services.gradle.org/distributions/gradle-2.10-all.zip.This full url is suggested by IDE such as Android Studio.If you want to download the full gradle,You can configure the wrapper task like this:
task wrapper(type: Wrapper) {
gradleVersion = '2.13'
distributionUrl = distributionUrl.replace("bin", "all")
}
How about:
myString.Any(x => Char.IsWhiteSpace(x))
Or if you like using the "method group" syntax:
myString.Any(Char.IsWhiteSpace)
thanks david_p,scala
conf.set("fs.hdfs.impl", classOf[org.apache.hadoop.hdfs.DistributedFileSystem].getName);
conf.set("fs.file.impl", classOf[org.apache.hadoop.fs.LocalFileSystem].getName);
or
<property>
<name>fs.hdfs.impl</name>
<value>org.apache.hadoop.hdfs.DistributedFileSystem</value>
</property>
First, I'd add a hidden input to your form to track the state of the form. Then, I'd use this jQuery snippet to set the value of the hidden input when something on the form changes:
$("form")
.find("input")
.change(function(){
if ($("#hdnFormChanged").val() == "no")
{
$("#hdnFormChanged").val("yes");
}
});
When your button is clicked, you can check the state of your hidden input:
$("#Button").click(function(){
if($("#hdnFormChanged").val() == "yes")
{
// handler code here...
}
});
This is my code for extracting pdf.
import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here' + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)
Please refer to this repo of mine for more details.
As said before, you can use td { display: block; }
but this defeats the purpose of using a table.
You can use table { table-layout: fixed; }
but maybe you want it to behave differently for some colums.
So the best way to achieve what you want would be to wrap your text in a <div>
and apply your CSS to the <div>
(not to the <td>
) like this :
td {
border: 1px solid black;
}
td > div {
width: 50px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
This SQL grants on all databases but just basic privileges. They're enough for Drupal or Wordpress and as a nicety, allows one developer account for local projects.
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP,
INDEX, ALTER, CREATE TEMPORARY TABLES
ON *.* TO 'username'@'localhost' IDENTIFIED BY 'password';
Like this:
#!/bin/bash
a=2462620
b=2462620
if [ "$a" -eq "$b" ]; then
echo "They're equal";
fi
Integers can be compared with these operators:
-eq # equal
-ne # not equal
-lt # less than
-le # less than or equal
-gt # greater than
-ge # greater than or equal
See this cheatsheet: https://devhints.io/bash#conditionals
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
You can use the following regex to get integer and floating values from a string:
re.findall(r'[\d\.\d]+', 'hello -34 42 +34.478m 88 cricket -44.3')
['34', '42', '34.478', '88', '44.3']
Thanks Rex
Here is an example for toggling bold, underline, and italics.
protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
{
if ( ActiveControl is RichTextBox r )
{
if ( keyData == ( Keys.Control | Keys.B ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Bold ); // XOR will toggle
return true;
}
if ( keyData == ( Keys.Control | Keys.U ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Underline ); // XOR will toggle
return true;
}
if ( keyData == ( Keys.Control | Keys.I ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Italic ); // XOR will toggle
return true;
}
}
return base.ProcessCmdKey( ref msg, keyData );
}
A simple way to do this is to call a logging function:
DEBUG = True
def log(s):
if DEBUG:
print s
log("hello world")
Then you can change the value of DEBUG
and run your code with or without logging.
The standard logging
module has a more elaborate mechanism for this.
**activity_main.xml**
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mukundwn.broadcastreceiver.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
**MainActivity.java**
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
broadcastReceiver =new MyBroadcastReceiver();
}
@Override
protected void onStart()
{
super.onStart();
IntentFilter intentFilter=new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(broadcastReceiver,intentFilter);
}
@Override
protected void onStop()
{
super.onStop();
unregisterReceiver(broadcastReceiver);
}
}
**MyBroadcastReceiver.java**
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by mukundwn on 12/02/18.
*/
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"hello received an sms",Toast.LENGTH_SHORT).show();
}
}
**Manifest.xml**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mukundwn.broadcastreceiver">
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVE"></action>
</intent-filter>
</receiver>
</application>
</manifest>
.innerText
doesnt work in Firefox.
.innerHTML
works in both the browsers.
Object.defineProperty(Results, "Active", {value : 'true',
writable : true,
enumerable : true,
configurable : true});
Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.
I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html
to achieve what you want .
Look at the code below :
HTML:
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>
JS :
createFormElement("Nickname","nickname")
function createFormElement(labelText, id) {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}
This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .
Moreover, when you use the process you mentioned in your post you get only [object Object]
. That is because when you call createProviderFormFields
, it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object
, then construct the html from it.
It's much easier to construct just the html and change the id
s of the label and input according to your needs.
Field.CurrentPage only works for Filter fields (also called page fields).
If you want to filter a row/column field, you have to cycle through the individual items, like so:
Sub FilterPivotField(Field As PivotField, Value)
Application.ScreenUpdating = False
With Field
If .Orientation = xlPageField Then
.CurrentPage = Value
ElseIf .Orientation = xlRowField Or .Orientation = xlColumnField Then
Dim i As Long
On Error Resume Next ' Needed to avoid getting errors when manipulating PivotItems that were deleted from the data source.
' Set first item to Visible to avoid getting no visible items while working
.PivotItems(1).Visible = True
For i = 2 To Field.PivotItems.Count
If .PivotItems(i).Name = Value Then _
.PivotItems(i).Visible = True Else _
.PivotItems(i).Visible = False
Next i
If .PivotItems(1).Name = Value Then _
.PivotItems(1).Visible = True Else _
.PivotItems(1).Visible = False
End If
End With
Application.ScreenUpdating = True
End Sub
Then, you would just call:
FilterPivotField ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode"), "K123223"
Naturally, this gets slower the more there are individual different items in the field. You can also use SourceName instead of Name if that suits your needs better.
For completeness, if you wanted to use replaceFirst, try this:
public static String cap1stChar(String userIdea)
{
String betterIdea = userIdea;
if (userIdea.length() > 0)
{
String first = userIdea.substring(0,1);
betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
}
return betterIdea;
}//end cap1stChar
In your html you can pass in an array for the name i.e
<input type="text" name="address[]" />
This way php will receive an array of addresses.
For everyone saying to get the bytes, copy it to MemoryStream
, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader
's built in ReadLine()
or ReadToEnd()
? I saw these weren't even mentioned, and they do everything for you.
I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult
that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:
string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";
string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine(); // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();
return path;
If you REALLY need a byte[]
instead of a string
for some reason, using my example, you can always do:
byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();
return toBytes;
(Returning toBytes
instead of path
.)
If you don't want ASCII
you can easily replace that with UTF8
, Unicode
, etc.
This sample works very well for me :
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.2</version>
<executions>
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
<propertyName>surefireArgLine</propertyName>
</configuration>
</execution>
<execution>
<id>pre-integration-test</id>
<goals>
<goal>prepare-agent-integration</goal>
</goals>
<configuration>
<destFile>${project.build.directory}/coverage-reports/jacoco-it.exec</destFile>
<!--<excludes>
<exclude>com.asimio.demo.rest</exclude>
<exclude>com.asimio.demo.service</exclude>
</excludes>-->
<propertyName>testArgLine</propertyName>
</configuration>
</execution>
<execution>
<id>post-integration-test</id>
<phase>post-integration-test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${project.build.directory}/coverage-reports/jacoco-it.exec</dataFile>
<outputDirectory>${project.reporting.outputDirectory}/jacoco-it</outputDirectory>
</configuration>
</execution>
<execution>
<id>post-unit-test</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
<outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
</configuration>
</execution>
<execution>
<id>merge-results</id>
<phase>verify</phase>
<goals>
<goal>merge</goal>
</goals>
<configuration>
<fileSets>
<fileSet>
<directory>${project.build.directory}/coverage-reports</directory>
<includes>
<include>*.exec</include>
</includes>
</fileSet>
</fileSets>
<destFile>${project.build.directory}/coverage-reports/aggregate.exec</destFile>
</configuration>
</execution>
<execution>
<id>post-merge-report</id>
<phase>verify</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${project.build.directory}/coverage-reports/aggregate.exec</dataFile>
<outputDirectory>${project.reporting.outputDirectory}/jacoco-aggregate</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<argLine>${surefireArgLine}</argLine>
<!--<skipTests>${skip.unit.tests}</skipTests>-->
<includes>
<include>**/*Test.java</include>
<!--<include>**/*MT.java</include>
<include>**/*Test.java</include>-->
</includes>
<!-- <skipTests>${skipUTMTs}</skipTests>-->
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<!--<skipTests>${skipTests}</skipTests>
<skipITs>${skipITs}</skipITs>-->
<argLine>${testArgLine}</argLine>
<includes>
<include>**/*IT.java</include>
</includes>
<!--<excludes>
<exclude>**/*UT*.java</exclude>
</excludes>-->
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
please import requestoptions from angular cors
import {RequestOptions, Request, Headers } from '@angular/http';
and add request options in your code like given below
let requestOptions = new RequestOptions({ headers:null, withCredentials:
true });
send request option in your api request
code snippet below-
let requestOptions = new RequestOptions({ headers:null,
withCredentials: true });
return this.http.get(this.config.baseUrl +
this.config.getDropDownListForProject, requestOptions)
.map(res =>
{
if(res != null)
{
return res.json();
//return true;
}
})
.catch(this.handleError);
}
and add CORS in your backend PHP code where all api request will land first.
try this and let me know if it is working or not i had a same issue i was adding CORS from angular5 that was not working then i added CORS to backend and it worked for me
The window.showModalDialog is deprecated (Intent to Remove: window.showModalDialog(), Removing showModalDialog from the Web platform). [...]The latest plan is to land the showModalDialog removal in Chromium 37. This means the feature will be gone in Opera 24 and Chrome 37, both of which should be released in September.[...]
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
Sadly this happens to me quite regularly as well and I use git stash
if I realized my mistake before git commit
and use git cherry-pick
otherwise, both commands are explained pretty well in other answers
I want to add a clarification for git checkout targetBranch
: this command will only preserve your working directory and staged snapshot if targetBranch has the same history as your current branch
If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally
@Amber's statement is not false, when you move to a newBranch,git checkout -b newBranch
, a new pointer is created and it is pointing to the exact same commit as your current branch.
In fact, if you happened to have an another branch that shares history with your current branch (both point at the same commit) you can "move your changes" by git checkout targetBranch
However, usually different branches means different history, and Git will not allow you to switch between these branches with a dirty working directory or staging area. in which case you can either do git checkout -f targetBranch
(clean and throwaway changes) or git stage
+ git checkout targetBranch
(clean and save changes), simply running git checkout targetBranch
will give an error:
error: Your local changes to the following files would be overwritten by checkout: ... Please commit your changes or stash them before you switch branches. Aborting
Percentage values are not applicable to border-width
in CSS. This is listed in the spec.
You will need to use JavaScript to calculate the percentage of the element's width or whatever length quantity you need, and apply the result in px
or similar to the element's borders.
The question is a bit unclear can't you just repeat the for loop?
a=[1,2,3]
for i in a:
print i
1
2
3
for i in a:
print i
1
2
3
VueJS can't pickup your changes to the state if you manipulate arrays like this.
As explained in Common Beginner Gotchas, you should use array methods like push, splice or whatever and never modify the indexes like this a[2] = 2
nor the .length property of an array.
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
f: 'DD-MM-YYYY',_x000D_
items: [_x000D_
"10-03-2017",_x000D_
"12-03-2017"_x000D_
]_x000D_
},_x000D_
methods: {_x000D_
_x000D_
cha: function(index, item, what, count) {_x000D_
console.log(item + " index > " + index);_x000D_
val = moment(this.items[index], this.f).add(count, what).format(this.f);_x000D_
_x000D_
this.items.$set(index, val)_x000D_
console.log("arr length: " + this.items.length);_x000D_
}_x000D_
}_x000D_
})
_x000D_
ul {_x000D_
list-style-type: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<div id="app">_x000D_
<ul>_x000D_
<li v-for="(index, item) in items">_x000D_
<br><br>_x000D_
<button v-on:click="cha(index, item, 'day', -1)">_x000D_
- day</button> {{ item }}_x000D_
<button v-on:click="cha(index, item, 'day', 1)">_x000D_
+ day</button>_x000D_
<br><br>_x000D_
</li>_x000D_
</ul>_x000D_
</div>
_x000D_
When you execute a script without typing "python" in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is:
C:\>assoc .py .py=Python.File
Next, you need to know how Windows is executing things with that extension. It's associated with the file type "Python.File", so this command shows what it will be doing:
C:\>ftype Python.File Python.File="c:\python26\python.exe" "%1" %*
So on my machine, when I type "blah.py foo", it will execute this exact command, with no difference in results than if I had typed the full thing myself:
"c:\python26\python.exe" "blah.py" foo
If you type the same thing, including the quotation marks, then you'll get results identical to when you just type "blah.py foo". Now you're in a position to figure out the rest of your problem for yourself.
(Or post more helpful information in your question, like actual cut-and-paste copies of what you see in the console. Note that people who do that type of thing get their questions voted up, and they get reputation points, and more people are likely to help them with good answers.)
Even if assoc and ftype display the correct information, it may happen that the arguments are stripped off. What may help in that case is directly fixing the relevant registry keys for Python. Set the
HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command
key to:
"C:\Python26\python26.exe" "%1" %*
Likely, previously, %*
was missing. Similarly, set
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command
to the same value. See http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command
The registry path may vary, use python26.exe
or python.exe
or whichever is already in the registry.
If you're after serialization, but won't need the data in other programs, I strongly recommend the shelve
module. Think of it as a persistent dictionary.
myData = shelve.open('/path/to/file')
# Check for values.
keyVar in myData
# Set values
myData[anotherKey] = someValue
# Save the data for future use.
myData.close()
Sort of solution using metatable...
local function preparetable(t)
setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end
local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)
if workingtable[456] then
...
end
I tried this code working for me,get image directly from url
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
use inside onCreate() method
new DownloadImageTask((ImageView) findViewById(R.id.image)) .execute("http://scoopak.com/wp-content/uploads/2013/06/free-hd-natural-wallpapers-download-for-pc.jpg");
Your ImageView has the attribute wrap_content
. I would think that the Image is centered inside the imageview but the imageview itself is not centered in the parentview. If you have only the imageview on the screen try match_parent
instead of wrap_content
. If you have more then one view in the layout you have to center the imageview.
In our case the problem was that we change the default root namespace name.
This is the Project Configuration screen
We finally decided to back to the original name and the problem was solved.
The problem actually was the dots in the Root namespace. With two dots (Name.Child.Child) it doesnt work. But with one (Name.ChidChild) works.
Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.
So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit
But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.
@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit
Or if you'd like them to select the file from which to write in the batch you could do the following.
@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit
i checked all Included JS Paths
Example Change this
<script src="js/bootstrap.min.js" type="text/javascript"></script>
TO
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>
Here's code to get the full path to the executing app:
Windows:
char pBuf[256];
size_t len = sizeof(pBuf);
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;
Linux:
int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
return bytes;
// http headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
@readfile($filepath.$filename);
I found this soludtion here and it work for me
For IPv4 addresses, you can use VARCHAR to store them as strings, but also look into storing them as long integesrs INT(11) UNSIGNED
. You can use MySQL's INET_ATON()
function to convert them to integer representation. The benefit of this is it allows you to do easy comparisons on them, like BETWEEN
queries
Try something like this:
#include <signal.h>
pid_t child_pid = -1 ; //Global
void kill_child(int sig)
{
kill(child_pid,SIGKILL);
}
int main(int argc, char *argv[])
{
signal(SIGALRM,(void (*)(int))kill_child);
child_pid = fork();
if (child_pid > 0) {
/*PARENT*/
alarm(30);
/*
* Do parent's tasks here.
*/
wait(NULL);
}
else if (child_pid == 0){
/*CHILD*/
/*
* Do child's tasks here.
*/
}
}
Late :( but I think this will solve your problem.
$("#controlId").val(SampleData [0].id).trigger("change");
After the data binding
$("#controlId").select2({
placeholder:"Select somthing",
data: SampleData // data from ajax controll
});
$("#controlId").val(SampleData[0].id).trigger("change");
This turned out to NOT be a bower problem, though it showed up for me with bower.
It seems to be a node-which problem. If a file is in the path, but has the setuid/setgid bit set, which will not find it.
Here is a files with the s bit set: (unix 'which' will find it with no problems).
ls -al /usr/local/bin -rwxrwsr-- 110 root nmt 5535636 Jul 17 2012 git
Here is a node-which attempt:
> which.sync('git')
Error: not found: git
I change the permissions (chomd 755 git). Now node-which can find it.
> which.sync('git')
'/usr/local/bin/git'
Hope this helps.
Having accessor methods is preferred to accessing fields directly, because it controls how fields are accessed (may impose data checking etc) and fits with interfaces (interfaces can not requires fields to be present, only methods).
Not glob
, but here's another way using a list comprehension:
extensions = 'txt mdown markdown'.split()
projectFiles = [f for f in os.listdir(projectDir)
if os.path.splitext(f)[1][1:] in extensions]
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
If you don't want execute assembly goal on package, you can use next command:
mvn package assembly:single
Here package is keyword.
Before increasing the max_connections variable, you have to check how many non-interactive connection you have by running show processlist command.
If you have many sleep connection, you have to decrease the value of the "wait_timeout" variable to close non-interactive connection after waiting some times.
SHOW SESSION VARIABLES LIKE 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout | 28800 |
+---------------+-------+
the value is in second, it means that non-interactive connection still up to 8 hours.
SET session wait_timeout=600; Query OK, 0 rows affected (0.00 sec)
After 10 minutes if the sleep connection still sleeping the mysql or MariaDB drop that connection.
You can provide one or multiple event types separated by a space.
So hover
equals mouseenter mouseleave
.
This is my sugession:
$("#foo").on("mouseenter mouseleave", function() {
// do some stuff
});
Using array_walk
$a = array("item1"=>"object1", "item2"=>"object2","item-n"=>"object-n");
$r=array();
array_walk($a, create_function('$b, $c', 'global $r; $r[]="$c=$b";'));
echo implode(', ', $r);
I removed compile 'com.android.support:support-v4:18.0.+' in dependencies, and it works
As we've already figured out in the question and the posted answers, there is an anti Web-scraping and a Bot detection service called "Distil Networks" in play here. And, according to the company CEO's interview:
Even though they can create new bots, we figured out a way to identify Selenium the a tool they’re using, so we’re blocking Selenium no matter how many times they iterate on that bot. We’re doing that now with Python and a lot of different technologies. Once we see a pattern emerge from one type of bot, then we work to reverse engineer the technology they use and identify it as malicious.
It'll take time and additional challenges to understand how exactly they are detecting Selenium, but what can we say for sure at the moment:
Decided to post it as an answer, since clearly:
Can a website detect when you are using selenium with chromedriver?
Yes.
Also, what I haven't experimented with is older selenium and older browser versions - in theory, there could be something implemented/added to selenium at a certain point that Distil Networks bot detector currently relies on. Then, if this is the case, we might detect (yeah, let's detect the detector) at what point/version a relevant change was made, look into changelog and changesets and, may be, this could give us more information on where to look and what is it they use to detect a webdriver-powered browser. It's just a theory that needs to be tested.
Use the .text()
function:
var text = $("<p> example ive got a string</P>").text();
Update: As Brilliand points out below, if the input string does not contain any tags and you are unlucky enough, it might be treated as a CSS selector. So this version is more robust:
var text = $("<div/>").html("<p> example ive got a string</P>").text();
yes, thats possible. just use the rgba-syntax for your background-color.
.menue{
background-color: rgba(255, 0, 0, 0.5); //semi-transparent red
}
So basically I'm looking at this in the wrong way. From what I see, this is not a React specific question, more of a JavaScript question in how do I combine two JavaScript objects together (without clobbering similarly named properties).
In this StackOverflow answer it explains it. How can I merge properties of two JavaScript objects dynamically?
In jQuery I can use the extend method.
This works for me:
<TextBox
Text="{Binding Path=UserInput, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Key="Return"
Command="{Binding Ok}"/>
</TextBox.InputBindings>
</TextBox>
My own take at @kvivek's script, with more easily machine parsable output:
#!/bin/sh
# Outputs OS Name, Version & misc. info in a machine-readable way.
# See also NeoFetch for a more professional and elaborate bash script:
# https://github.com/dylanaraps/neofetch
SEP=","
PRINT_HEADER=false
print_help() {
echo "`basename $0` - Outputs OS Name, Version & misc. info"
echo "in a machine-readable way."
echo
echo "Usage:"
echo " `basename $0` [OPTIONS]"
echo "Options:"
echo " -h, --help print this help message"
echo " -n, --names print a header line, naming the fields"
echo " -s, --separator SEP overrides the default field-separator ('$SEP') with the supplied one"
}
# parse command-line args
while [ $# -gt 0 ]
do
arg="$1"
shift # past switch
case "${arg}" in
-h|--help)
print_help
exit 0
;;
-n|--names)
PRINT_HEADER=true
;;
-s|--separator)
SEP="$1"
shift # past value
;;
*) # non-/unknown option
echo "Unknown switch '$arg'" >&2
print_help
;;
esac
done
OS=`uname -s`
DIST="N/A"
REV=`uname -r`
MACH=`uname -m`
PSUEDONAME="N/A"
GetVersionFromFile()
{
VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}
if [ "${OS}" = "SunOS" ] ; then
DIST=Solaris
DIST_VER=`uname -v`
# also: cat /etc/release
elif [ "${OS}" = "AIX" ] ; then
DIST="${OS}"
DIST_VER=`oslevel -r`
elif [ "${OS}" = "Linux" ] ; then
if [ -f /etc/redhat-release ] ; then
DIST='RedHat'
PSUEDONAME=`sed -e 's/.*\(//' -e 's/\)//' /etc/redhat-release `
DIST_VER=`sed -e 's/.*release\ //' -e 's/\ .*//' /etc/redhat-release `
elif [ -f /etc/SuSE-release ] ; then
DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
DIST_VER=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
elif [ -f /etc/mandrake-release ] ; then
DIST='Mandrake'
PSUEDONAME=`sed -e 's/.*\(//' -e 's/\)//' /etc/mandrake-release`
DIST_VER=`sed -e 's/.*release\ //' -e 's/\ .*//' /etc/mandrake-release`
elif [ -f /etc/debian_version ] ; then
DIST="Debian"
DIST_VER=`cat /etc/debian_version`
PSUEDONAME=`lsb_release -a 2> /dev/null | grep '^Codename:' | sed -e 's/.*[[:space:]]//'`
#elif [ -f /etc/gentoo-release ] ; then
#TODO
#elif [ -f /etc/slackware-version ] ; then
#TODO
elif [ -f /etc/issue ] ; then
# We use this indirection because /etc/issue may look like
# "Debian GNU/Linux 10 \n \l"
ISSUE=`cat /etc/issue`
ISSUE=`echo -e "${ISSUE}" | head -n 1 | sed -e 's/[[:space:]]\+$//'`
DIST=`echo -e "${ISSUE}" | sed -e 's/[[:space:]].*//'`
DIST_VER=`echo -e "${ISSUE}" | sed -e 's/.*[[:space:]]//'`
fi
if [ -f /etc/UnitedLinux-release ] ; then
DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
fi
# NOTE `sed -e 's/.*(//' -e 's/).*//' /proc/version`
# is an option that worked ~ 2010 and earlier
fi
if $PRINT_HEADER
then
echo "OS${SEP}Distribution${SEP}Distribution-Version${SEP}Pseudo-Name${SEP}Kernel-Revision${SEP}Machine-Architecture"
fi
echo "${OS}${SEP}${DIST}${SEP}${DIST_VER}${SEP}${PSUEDONAME}${SEP}${REV}${SEP}${MACH}"
NOTE: Only tested on Debian 11
osInfo
output:
Linux,Debian,10.0,buster,4.19.0-5-amd64,x86_64
osInfo --names -s "\t| "
output:
OS | Distribution | Distribution-Version | Pseudo-Name | Kernel-Revision | Machine-Architecture
Linux | Debian | 10.0 | buster | 4.19.0-5-amd64 | x86_64
osInfo | awk -e 'BEGIN { FS=","; } { print $2 " " $3 " (" $4 ")" }'
output:
Debian 10.0 (buster)
I saw this post at least twice, because the accepted answer is hard to remeber for me(I rarely use z
or j
flags and they are seems not platform independant).
The standard never says clearly the exact data length of size_t
, so I suggest you should first check the length size_t
on your platform then select one of them:
if sizeof(size_t) == 4 use PRIu32
if sizeof(size_t) == 8 use PRIu64
And I suggest using stdint
types instead of raw data types for consistancy.
In any sql server version you could use a variable for the total of all grades like this:
declare @countOfAll decimal(18, 4)
select @countOfAll = COUNT(*) from Grades
select
Grade, COUNT(*) / @countOfAll * 100
from Grades
group by Grade
_x000D_
_x000D_
/* add javascript*/_x000D_
{_x000D_
document.getElementById('abc 1').style.display='none';_x000D_
}_x000D_
/* after that add html*/_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title>...</title>_x000D_
</head>_x000D_
<body>_x000D_
<table border = 2>_x000D_
<tr id = "abc 1">_x000D_
<td>abcd</td>_x000D_
</tr>_x000D_
<tr id ="abc 2">_x000D_
<td>efgh</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
var fs = require("fs");
var filename = "./index.html";
function start(resp) {
resp.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resp.write(data);
resp.end();
});
}
Simple tabulation of the output:
a = 0.3333333
b = 200/3
print("variable a variable b")
print("%10.2f %10.2f" % (a, b))
output:
variable a variable b
0.33 66.67
%10.2f: 10 is the minimum length and 2 is the number of decimal places.
Another way to use .ui in your code is:
from PyQt4 import QtCore, QtGui, uic
class MyWidget(QtGui.QWidget)
...
#somewhere in constructor:
uic.loadUi('MyWidget.ui', self)
both approaches are good. Do not forget, that if you use Qt resource files (extremely useful) for icons and so on, you must compile it too:
pyrcc4.exe -o ui/images_rc.py ui/images/images.qrc
Note, when uic
compiles interface, it adds 'import images_rc' at the end of .py file, so you must compile resources into the file with this name, or rename it in generated code.
Try using pandoc
pandoc -f html -t docx -o output.docx input.html
If the input or output format is not specified explicitly, pandoc will attempt to guess it from the extensions of the input and output filenames.
— pandoc manual
So you can even use
pandoc -o output.docx input.html
To get the current directory full path:
os.path.realpath('.')
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
All major browsers now include native JSON encoding/decoding.
// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject);
// To decode (This produces an object)
var obj = JSON.parse(json_str);
Note that only valid JSON data will be encoded. For example:
var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"
Valid JSON types are: objects, strings, numbers, arrays, true
, false
, and null
.
Some JSON resources:
string c = Char.ConvertFromUtf32(65);
c will contain "A"
Bubble sort can be used here:
//Time complexity: O(n^2)
public static int[] bubbleSort(final int[] arr) {
if (arr == null || arr.length <= 1) {
return arr;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 1; j < arr.length - i; j++) {
if (arr[j - 1] > arr[j]) {
arr[j] = arr[j] + arr[j - 1];
arr[j - 1] = arr[j] - arr[j - 1];
arr[j] = arr[j] - arr[j - 1];
}
}
}
return arr;
}
Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:
git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit
If you want to still have it in your local repository and only remove it from the remote, then you can use:
git push origin +HEAD^:<name of your branch, most likely 'master'>
The standard MIME type for ZIP files is application/zip
. The types for the files inside the ZIP does not matter for the MIME type.
As always, it ultimately depends on your server setup.
above solution doesn't work for me for unknown reason. below is my workaround which was worked successfully.
1) DO NOT generate a new ssh key by using command ssh-keygen -t rsa -C"[email protected]"
, you can delete existing SSH keys.
2) but use Git GUI, -> "Help" -> "Show ssh key" -> "Generate key", the key will saved to ssh automatically and no need to use ssh-add
anymore.
Delegates are extremely useful when wanting to declare a block of code that you want to pass around. For example when using a generic retry mechanism.
Pseudo:
function Retry(Delegate func, int numberOfTimes)
try
{
func.Invoke();
}
catch { if(numberOfTimes blabla) func.Invoke(); etc. etc. }
Or when you want to do late evaluation of code blocks, like a function where you have some Transform
action, and want to have a BeforeTransform
and an AfterTransform
action that you can evaluate within your Transform function, without having to know whether the BeginTransform
is filled, or what it has to transform.
And of course when creating event handlers. You don't want to evaluate the code now, but only when needed, so you register a delegate that can be invoked when the event occurs.
For me working solution is:
ON REMOTE:
git checkout -b some_tmp_name
ON LOCAL:
git push
ON REMOTE:
git checkout master
git branch -d some_tmp_name
But this is not the real solution it's just workaround.
I think you want to make objects from array and combine it with an old object (BODY.recipients.values), if it's then you may do it using $.extent
(because you are using jQuery
/tagged) method after prepare the object from array
var BODY = {
"recipients": {
"values": []
},
"subject": 'TitleOfSubject',
"body": 'This is the message body.'
}
var values = [],
names = ['sheikh', 'muhammed', 'Answer', 'Uddin', 'Heera']; // for testing
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": { "_path": "/people/"+names[ln] }
};
values.push(item1);
}
// Now merge with BODY
$.extend(BODY.recipients.values, values);
Prefix the call with Module2 (ex. Module2.IDLE
). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.
unset
is the command you're looking for.
unset GNUPLOT_DRIVER_DIR
SELECT COUNT(job_id) FROM jobs WHERE posted_date < NOW()-30;
Now()
returns the current Date and Time.
Built a modal popup example using syarul's jsFiddle link. Here is the updated fiddle.
Created an angular directive called modal and used in html. Explanation:-
HTML
<div ng-controller="MainCtrl" class="container">
<button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
<button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
<button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
<button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
<modal visible="showModal">
Any additional data / buttons
</modal>
</div>
On button click toggleModal() function is called with the button message as parameter. This function toggles the visibility of popup. Any tags that you put inside will show up in the popup as content since ng-transclude is placed on modal-body in the directive template.
JS
var mymodal = angular.module('mymodal', []);
mymodal.controller('MainCtrl', function ($scope) {
$scope.showModal = false;
$scope.buttonClicked = "";
$scope.toggleModal = function(btnClicked){
$scope.buttonClicked = btnClicked;
$scope.showModal = !$scope.showModal;
};
});
mymodal.directive('modal', function () {
return {
template: '<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
'<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace:true,
scope:true,
link: function postLink(scope, element, attrs) {
scope.title = attrs.title;
scope.$watch(attrs.visible, function(value){
if(value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
UPDATE
<!doctype html>
<html ng-app="mymodal">
<body>
<div ng-controller="MainCtrl" class="container">
<button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
<button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
<button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
<button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
<modal visible="showModal">
Any additional data / buttons
</modal>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Scripts -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<!-- App -->
<script>
var mymodal = angular.module('mymodal', []);
mymodal.controller('MainCtrl', function ($scope) {
$scope.showModal = false;
$scope.buttonClicked = "";
$scope.toggleModal = function(btnClicked){
$scope.buttonClicked = btnClicked;
$scope.showModal = !$scope.showModal;
};
});
mymodal.directive('modal', function () {
return {
template: '<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
'<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace:true,
scope:true,
link: function postLink(scope, element, attrs) {
scope.$watch(attrs.visible, function(value){
if(value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
</script>
</body>
</html>
UPDATE 2 restrict : 'E' : directive to be used as an HTML tag (element). Example in our case is
<modal>
Other values are 'A' for attribute
<div modal>
'C' for class (not preferable in our case because modal is already a class in bootstrap.css)
<div class="modal">
You could also use the below, the iif avoids the case statement and only adds ellipses when required (only good in SQL Server 2012 and later) and the case statement is more ANSI compliant (but more verbose)
SELECT
col, LEN(col),
col2, LEN(col2),
col3, LEN(col3) FROM (
SELECT
col,
LEFT(x.col, 15) + (IIF(len(x.col) > 15, '...', '')) AS col2,
LEFT(x.col, 15) + (CASE WHEN len(x.col) > 15 THEN '...' ELSE '' END) AS col3
from (
select 'this is a long string. One that is longer than 15 characters' as col
UNION
SELECT 'short string' AS col
UNION
SELECT 'string==15 char' AS col
UNION
SELECT NULL AS col
UNION
SELECT '' AS col
) x
) y
Frequently we deal with other fellow java programmers work which create these Stored Procedure. and we do not want to mess around with it. but there is possibility you get the result set where these exec sample return 0 (almost Stored procedure call returning zero).
check this sample :
public void generateINOUT(String USER, int DPTID){
try {
conUrl = JdbcUrls + dbServers +";databaseName="+ dbSrcNames+";instance=MSSQLSERVER";
con = DriverManager.getConnection(conUrl,dbUserNames,dbPasswords);
//stat = con.createStatement();
con.setAutoCommit(false);
Statement st = con.createStatement();
st.executeUpdate("DECLARE @RC int\n" +
"DECLARE @pUserID nvarchar(50)\n" +
"DECLARE @pDepartmentID int\n" +
"DECLARE @pStartDateTime datetime\n" +
"DECLARE @pEndDateTime datetime\n" +
"EXECUTE [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] \n" +
""+USER +
"," +DPTID+
",'"+STARTDATE +
"','"+ENDDATE+"'");
ResultSet rs = st.getGeneratedKeys();
while (rs.next()){
String userID = rs.getString("UserID");
Timestamp timeIN = rs.getTimestamp("timeIN");
Timestamp timeOUT = rs.getTimestamp ("timeOUT");
int totTime = rs.getInt ("totalTime");
int pivot = rs.getInt ("pivotvalue");
timeINS = sdz.format(timeIN);
userIN.add(timeINS);
timeOUTS = sdz.format(timeOUT);
userOUT.add(timeOUTS);
System.out.println("User : "+userID+" |IN : "+timeIN+" |OUT : "+timeOUT+"| Total Time : "+totTime+" | PivotValue : "+pivot);
}
con.commit();
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
if (e.getCause() != null) {
e.getCause().printStackTrace();}
}
}
I came to this solutions after few days trial and error, googling and get confused ;) it execute below Stored Procedure :
USE [AccessManager]
GO
/****** Object: StoredProcedure [dbo].[SP_GenerateInOutDetailReportSimple]
Script Date: 04/05/2013 15:54:11 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_GenerateInOutDetailReportSimple]
(
@pUserID nvarchar(50),
@pDepartmentID int,
@pStartDateTime datetime,
@pEndDateTime datetime
)
AS
Declare @ErrorCode int
Select @ErrorCode = @@Error
Declare @TransactionCountOnEntry int
If @ErrorCode = 0
Begin
Select @TransactionCountOnEntry = @@TranCount
BEGIN TRANSACTION
End
If @ErrorCode = 0
Begin
-- Create table variable instead of SQL temp table because report wont pick up the temp table
DECLARE @tempInOutDetailReport TABLE
(
UserID nvarchar(50),
LogDate datetime,
LogDay varchar(20),
TimeIN datetime,
TimeOUT datetime,
TotalTime int,
RemarkTimeIn nvarchar(100),
RemarkTimeOut nvarchar(100),
TerminalIPTimeIn varchar(50),
TerminalIPTimeOut varchar(50),
TerminalSNTimeIn nvarchar(50),
TerminalSNTimeOut nvarchar(50),
PivotValue int
)
-- Declare variables for the while loop
Declare @LogUserID nvarchar(50)
Declare @LogEventID nvarchar(50)
Declare @LogTerminalSN nvarchar(50)
Declare @LogTerminalIP nvarchar(50)
Declare @LogRemark nvarchar(50)
Declare @LogTimestamp datetime
Declare @LogDay nvarchar(20)
-- Filter off userID, departmentID, StartDate and EndDate if specified, only process the remaining logs
-- Note: order by user then timestamp
Declare LogCursor Cursor For
Select distinct access_event_logs.USERID, access_event_logs.EVENTID,
access_event_logs.TERMINALSN, access_event_logs.TERMINALIP,
access_event_logs.REMARKS, access_event_logs.LOCALTIMESTAMP, Datename(dw,access_event_logs.LOCALTIMESTAMP) AS WkDay
From access_event_logs
Left Join access_user on access_user.User_ID = access_event_logs.USERID
Left Join access_user_dept on access_user.User_ID = access_user_dept.User_ID
Where ((Dept_ID = @pDepartmentID) OR (@pDepartmentID IS NULL))
And ((access_event_logs.USERID LIKE '%' + @pUserID + '%') OR (@pUserID IS NULL))
And ((access_event_logs.LOCALTIMESTAMP >= @pStartDateTime ) OR (@pStartDateTime IS NULL))
And ((access_event_logs.LOCALTIMESTAMP < DATEADD(day, 1, @pEndDateTime) ) OR (@pEndDateTime IS NULL))
And (access_event_logs.USERID != 'UNKNOWN USER') -- Ignore UNKNOWN USER
Order by access_event_logs.USERID, access_event_logs.LOCALTIMESTAMP
Open LogCursor
Fetch Next
From LogCursor
Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay
-- Temp storage for IN event details
Declare @InEventUserID nvarchar(50)
Declare @InEventDay nvarchar(20)
Declare @InEventTimestamp datetime
Declare @InEventRemark nvarchar(100)
Declare @InEventTerminalIP nvarchar(50)
Declare @InEventTerminalSN nvarchar(50)
-- Temp storage for OUT event details
Declare @OutEventUserID nvarchar(50)
Declare @OutEventTimestamp datetime
Declare @OutEventRemark nvarchar(100)
Declare @OutEventTerminalIP nvarchar(50)
Declare @OutEventTerminalSN nvarchar(50)
Declare @CurrentUser varchar(50) -- used to indicate when we change user group
Declare @CurrentDay varchar(50) -- used to indicate when we change day
Declare @FirstEvent int -- indicate the first event we received
Declare @ReceiveInEvent int -- indicate we have received an IN event
Declare @PivotValue int -- everytime we change user or day - we reset it (reporting purpose), if same user..keep increment its value
Declare @CurrTrigger varchar(50) -- used to keep track of the event of the current event log trigger it is handling
Declare @CurrTotalHours int -- used to keep track of total hours of the day of the user
Declare @FirstInEvent datetime
Declare @FirstInRemark nvarchar(100)
Declare @FirstInTerminalIP nvarchar(50)
Declare @FirstInTerminalSN nvarchar(50)
Declare @FirstRecord int -- indicate another day of same user
Set @PivotValue = 0 -- initialised
Set @CurrentUser = '' -- initialised
Set @FirstEvent = 1 -- initialised
Set @ReceiveInEvent = 0 -- initialised
Set @CurrTrigger = '' -- Initialised
Set @CurrTotalHours = 0 -- initialised
Set @FirstRecord = 1 -- initialised
Set @CurrentDay = '' -- initialised
While @@FETCH_STATUS = 0
Begin
-- use to track current log trigger
Set @CurrTrigger =LOWER(@LogEventID)
If (@CurrentUser != '' And @CurrentUser != @LogUserID) -- new batch of user
Begin
If @ReceiveInEvent = 1 -- previous IN event is not cleared (no OUT is found)
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else -- same day
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
-- invalid row (only has IN event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn,
TerminalSNTimeIn, PivotValue, LogDate )
values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP,
@InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
Set @FirstEvent = 1 -- Reset flag (we are having a new user group)
Set @ReceiveInEvent = 0 -- Reset
Set @PivotValue = 0 -- Reset
--Set @CurrentDay = '' -- Reset
End
If LOWER(@LogEventID) = 'in' -- IN event
Begin
If @ReceiveInEvent = 1 -- previous IN event is not cleared (no OUT is found)
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Begin
Set @PivotValue = 0 -- Reset
--Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
-- RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
-- LogDate)
--values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp, @CurrTotalHours,
-- @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
-- DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
-- invalid row (only has IN event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn,
TerminalSNTimeIn, PivotValue, LogDate )
values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP,
@InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
If((@CurrentDay != @LogDay And @CurrentDay != '') Or (@CurrentUser != @LogUserID And @CurrentUser != '') )
Begin
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
LogDate)
values( @CurrentUser, @CurrentDay, @FirstInEvent, @OutEventTimestamp, @CurrTotalHours,
@FirstInRemark, @OutEventRemark, @FirstInTerminalIP, @OutEventTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
Set @FirstRecord = 1
End
-- Save it
Set @InEventUserID = @LogUserID
Set @InEventDay = @LogDay
Set @InEventTimestamp = @LogTimeStamp
Set @InEventRemark = @LogRemark
Set @InEventTerminalIP = @LogTerminalIP
Set @InEventTerminalSN = @LogTerminalSN
If (@FirstRecord = 1) -- save for first in event record of the day
Begin
Set @FirstInEvent = @LogTimestamp
Set @FirstInRemark = @LogRemark
Set @FirstInTerminalIP = @LogTerminalIP
Set @FirstInTerminalSN = @LogTerminalSN
Set @CurrTotalHours = 0 --initialise total hours for another day
End
Set @FirstRecord = 0 -- no more first record of the day
Set @ReceiveInEvent = 1 -- indicate we have received an "IN" event
Set @FirstEvent = 0 -- no more "first" event
End
Else If LOWER(@LogEventID) = 'out' -- OUT event
Begin
If @FirstEvent = 1 -- the first OUT record when change users
Begin
-- Check day
If (@CurrentDay != @LogDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @LogDay -- update the day
-- Only an OUT event (no IN event) - invalid record but we show it anyway
Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
PivotValue, LogDate )
values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)))
Set @FirstEvent = 0 -- not "first" anymore
End
Else -- Not first event
Begin
If @ReceiveInEvent = 1 -- if there are IN event previously
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
Set @CurrTotalHours = @CurrTotalHours + DATEDIFF(second,@InEventTimestamp, @LogTimeStamp) -- update total time
Set @OutEventRemark = @LogRemark
Set @OutEventTerminalIP = @LogTerminalIP
Set @OutEventTerminalSN = @LogTerminalSN
Set @OutEventTimestamp = @LogTimestamp
-- valid row
--Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
-- RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
-- LogDate)
--values( @LogUserID, @InEventDay, @InEventTimestamp, @LogTimestamp, Datediff(second, @InEventTimestamp, @LogTimeStamp),
-- @InEventRemark, @LogRemark, @InEventTerminalIP, @LogTerminalIP, @InEventTerminalSN, @LogTerminalSN, @PivotValue,
-- DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
Set @ReceiveInEvent = 0 -- Reset
End
Else -- no IN event previously
Begin
-- Check day
If (@CurrentDay != @LogDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @LogDay -- update the day
-- invalid row (only has OUT event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
PivotValue, LogDate )
values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)) )
End
End
End
Set @CurrentUser = @LogUserID -- update user
Fetch Next
From LogCursor
Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay
End
-- Need to handle the last log if its IN log as it will not be processed by the while loop
if @CurrTrigger='in'
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else -- same day
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
-- invalid row (only has IN event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn,
TerminalSNTimeIn, PivotValue, LogDate )
values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP,
@InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
else if @CurrTrigger = 'out'
Begin
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
LogDate)
values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp, @CurrTotalHours,
@FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
Close LogCursor
Deallocate LogCursor
Select *
From @tempInOutDetailReport tempTable
Left Join access_user on access_user.User_ID = tempTable.UserID
Order By tempTable.UserID, LogDate
End
If @@TranCount > @TransactionCountOnEntry
Begin
If @ErrorCode = 0
COMMIT TRANSACTION
Else
ROLLBACK TRANSACTION
End
return @ErrorCode
you will get the "java SQL Code" by right click on stored procedure in your database. something like this :
DECLARE @RC int
DECLARE @pUserID nvarchar(50)
DECLARE @pDepartmentID int
DECLARE @pStartDateTime datetime
DECLARE @pEndDateTime datetime
-- TODO: Set parameter values here.
EXECUTE @RC = [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple]
@pUserID,@pDepartmentID,@pStartDateTime,@pEndDateTime
GO
check the query String I've done, that is your homework ;) so sorry answering this long, this is my first answer since I register few weeks ago to get answer.
Basically, if you're on a 64-bit machine, IIS 7 is not (by default) serving 32-bit apps, which the database engine operates on. So here is exactly what you do:
1) ensure that the 2007 database engine is installed, this can be downloaded at: http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
2) open IIS7 manager, and open the Application Pools area. On the right sidebar, you will see an option that says "Set application pool defaults". Click it, and a window will pop up with the options.
3) the second field down, which says 'Enable 32-bit applications' is probably set to FALSE by default. Simply click where it says 'false' to change it to 'true'.
4) Restart your app pool (you can do this by hitting RECYCLE instead of STOP then START, which will also work).
5) done, and your error message will go away.
Why didn't you try to define is_private
in your models as default=False
?
class Foo(models.Models):
is_private = models.BooleanField(default=False)
You may simply use MultipartHttpServletRequest
Example:
@RequestMapping(value={"/upload"}, method = RequestMethod.POST,produces = "text/html; charset=utf-8")
@ResponseBody
public String upload(MultipartHttpServletRequest request /*@RequestBody MultipartFile file*/){
String responseMessage = "OK";
MultipartFile file = request.getFile("file");
String param = request.getParameter("param");
try {
System.out.println(file.getOriginalFilename());
System.out.println("some param = "+param);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8));
// read file
}
catch(Exception ex){
ex.printStackTrace();
responseMessage = "fail";
}
return responseMessage;
}
Where parameters names in request.getParameter()
must be same with corresponding frontend names.
Note, that file extracted via getFile()
while other additional parameters extracted via getParameter()
tigeravatar and Jean-François Corbett suggested to use this formula to generate the string right of the last occurrence of the "\" character
=TRIM(RIGHT(SUBSTITUTE(A1,"\",REPT(" ",LEN(A1))),LEN(A1)))
If the character used as separator is space, " ", then the formula has to be changed to:
=SUBSTITUTE(RIGHT(SUBSTITUTE(A1," ",REPT("{",LEN(A1))),LEN(A1)),"{","")
No need to mention, the "{" character can be replaced with any character that would not "normally" occur in the text to process.
In case you need to convert an entire column of data (from pandas DataFrame), then first convert it (pandas Series) to the datetime format using to_datetime
and finally use .dt.strftime
:
def conv_dates_series(df, col, old_date_format, new_date_format):
df[col] = pd.to_datetime(df[col], format=old_date_format).dt.strftime(new_date_format)
return(df)
Sample usage:
import pandas as pd
test_df = pd.DataFrame({"Dates": ["1900-01-01", "1999-12-31"]})
old_date_format='%d/%m/%Y'
new_date_format='%Y-%m-%d'
conv_dates_series(test_df, "Dates", old_date_format, new_date_format)
The single star *
unpacks the sequence/collection into positional arguments, so you can do this:
def sum(a, b):
return a + b
values = (1, 2)
s = sum(*values)
This will unpack the tuple so that it actually executes as:
s = sum(1, 2)
The double star **
does the same, only using a dictionary and thus named arguments:
values = { 'a': 1, 'b': 2 }
s = sum(**values)
You can also combine:
def sum(a, b, c, d):
return a + b + c + d
values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
s = sum(*values1, **values2)
will execute as:
s = sum(1, 2, c=10, d=15)
Also see section 4.7.4 - Unpacking Argument Lists of the Python documentation.
Additionally you can define functions to take *x
and **y
arguments, this allows a function to accept any number of positional and/or named arguments that aren't specifically named in the declaration.
Example:
def sum(*values):
s = 0
for v in values:
s = s + v
return s
s = sum(1, 2, 3, 4, 5)
or with **
:
def get_a(**values):
return values['a']
s = get_a(a=1, b=2) # returns 1
this can allow you to specify a large number of optional parameters without having to declare them.
And again, you can combine:
def sum(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if options["neg"]:
s = -s
return s
s = sum(1, 2, 3, 4, 5) # returns 15
s = sum(1, 2, 3, 4, 5, neg=True) # returns -15
s = sum(1, 2, 3, 4, 5, neg=False) # returns 15
Double escaping is required when presented as a string.
Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html
That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.
Check you are including all the source files within your solution that you are referencing.
If you are not including the source file (and thus the implementation) for the class Field
in your project it won't be built and you will be unable to link during compilation.
Alternatively, perhaps you are using a static or dynamic library and have forgotten to tell the linker about the .lib
s?
Using a combination of SUBSTR, INSTR, and NVL (for strings without an underscore) will return what you want:
SELECT NVL(SUBSTR('ABC_blah', 0, INSTR('ABC_blah', '_')-1), 'ABC_blah') AS output
FROM DUAL
output
------
ABC
SELECT NVL(SUBSTR(t.column, 0, INSTR(t.column, '_')-1), t.column) AS output
FROM YOUR_TABLE t
If using Oracle10g+, you can use regex via REGEXP_SUBSTR.
To go one step further, you could declare a type pointer to a function signature like:
interface myCallbackType { (myArgument: string): void }
and use it like this:
public myCallback : myCallbackType;
This is an old but still very relevant question, so I'll add this: What's the first thing you look for when you open up a class file that you may or may not have read before? Fields? Properties? I've realized from experience that almost invariably I go hunting for the constructors, because the most basic thing to understand is how this object is constructed.
Therefore, I've started putting constructors first in class files, and the result has been psychologically very positive. The standard recommendation of putting constructors after a bunch of other things feels dissonant.
The upcoming primary constructor feature in C# 6 provides evidence that the natural place for a constructor is at the very top of a class - in fact primary constructors are specified even before the open brace.
It's funny how much of a difference a reordering like this makes. It reminds me of how using
statements used to be ordered - with the System namespaces first. Visual Studio's "Organize Usings" command used this order. Now using
s are just ordered alphabetically, with no special treatment given to System namespaces. The result just feels simpler and cleaner.
If your repo have 2FA enabled. Highly suggest to use the app provided by github.com Here is the link: https://desktop.github.com/
After you downloaded it and installed it. Follow the withard, the app will ask you to provide the one time password for login. Once you filled in the one time password, you could see your repo/projects now.
In C/C++, pointers and arrays are (almost) equivalent.
int *a; a[0];
will return *a
, and a[1];
will return *(a + 1)
But array can't change the pointer it points to while pointer can.
new int[n]
will allocate some spaces for the "array"
In Chrome, use JSONView to view formatted JSON.
To view "local" *.json files: - after install You must open the Extensions option from Window menu. - Check box next to "Allow Access to File URLs" - note that save is automatic (i.e. no explicit save necessary)
Re-open the *.json file and it should be formatted.
I was facing same issue i changed background color of view to layout background color u can do like this:
edit_countflag.setBackgroundColor(Color.parseColor("#ffffff"));
//then set the image
edit_countflag.setImageResource(R.drawable.flag_id);
The trick of appending "*" can be made to work when the new extension is shorter. You need to pad the new extension with blanks, which can only be done by enclosing the destination file name in quotes. For example:
xcopy foo.shtml "foo.html *"
This will copy and rename without prompting.
"That's not a bug, it's a feature!" (I once saw a VW Beetle in the Microsoft parking lot with the vanity plate "FEATURE".) These semantics for rename go all the way back to when I wrote DOS v.1. Characters in the new name are substituted one by one for characters in the old name, unless a wildcard character (? or *) is present in the new name. Without adding the blank(s) to the new name, remaining characters are copied from the old name.
To complement the existing, helpful answers; tip of the hat to QZ Support for encouraging me to post a separate answer:
Two distinct mechanisms come into play here:
(a) whether cut
itself requires the delimiter (space, in this case) passed to the -d
option to be a separate argument or whether it's acceptable to append it directly to -d
.
(b) how the shell generally parses arguments before passing them to the command being invoked.
(a) is answered by a quote from the POSIX guidelines for utilities (emphasis mine)
If the SYNOPSIS of a standard utility shows an option with a mandatory option-argument [...] a conforming application shall use separate arguments for that option and its option-argument. However, a conforming implementation shall also permit applications to specify the option and option-argument in the same argument string without intervening characters.
In other words: In this case, because -d
's option-argument is mandatory, you can choose whether to specify the delimiter as:
-d
.Once you've chosen (s) or (d), it is the shell's string-literal parsing - (b) - that matters:
With approach (s), all of the following forms are EQUIVALENT:
-d ' '
-d " "
-d \<space> # <space> used to represent an actual space for technical reasons
With approach (d), all of the following forms are EQUIVALENT:
-d' '
-d" "
"-d "
'-d '
d\<space>
The equivalence is explained by the shell's string-literal processing:
All solutions above result in the exact same string (in each group) by the time cut
sees them:
(s): cut
sees -d
, as its own argument, followed by a separate argument that contains a space char - without quotes or \
prefix!.
(d): cut
sees -d
plus a space char - without quotes or \
prefix! - as part of the same argument.
The reason the forms in the respective groups are ultimately identical is twofold, based on how the shell parses string literals:
'...'
is taken literally and forms a single argument"..."
also forms a single argument, but is subject to interpolation (expands variable references such as $var
, command substitutions ($(...)
or `...`
), or arithmetic expansions ($(( ... ))
).\
-quoting of individual characters: a \
preceding a single character causes that character to be interpreted as a literal.'...'
or "..."
or \
instances) - thus, the command being invoked never sees the quote characters.If you do things with time and dates Carbon is you best friend;
Install the package then:
$theDay = Carbon::make("2010-01-21 00:00:00.0");
$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))
lt = less than, gt = greater than
As in the question:
$theDay->gt(Carbon::today()) ? true : false;
and much more;
If your builds on TravisCI are failing for this particular reason, you can resolve the issue by updating the Django Extensions in your requirements.txt
pip install --upgrade django-extensions
This will update the extensions to use Django 2+ modules.
Pushing multiple objects at once often depends on how are you declaring your array
.
This is how I did
//declaration
productList= [] as any;
now push
records
this.productList.push(obj.lenght, obj2.lenght, items);
You'll need to use a static
readonly
list instead. And if you want the list to be immutable then you might want to consider using ReadOnlyCollection<T>
rather than List<T>
.
private static readonly ReadOnlyCollection<string> _metrics =
new ReadOnlyCollection<string>(new[]
{
SourceFile.LOC,
SourceFile.MCCABE,
SourceFile.NOM,
SourceFile.NOA,
SourceFile.FANOUT,
SourceFile.FANIN,
SourceFile.NOPAR,
SourceFile.NDC,
SourceFile.CALLS
});
public static ReadOnlyCollection<string> Metrics
{
get { return _metrics; }
}
two more ways - fast and backward compatible .
fltmc >nul 2>&1 && (
echo has admin permissions
) || (
echo has NOT admin permissions
)
fltmc
command is available on every windows system since XP so this should be pretty portable.
One more really fast solution tested on XP
,8.1
,7
- there's one specific variable =::
which is presented only if the console session has no admin privileges.As it is not so easy to create variable that contains =
in it's name this is comparatively reliable way to check for admin permission (it does not call external executables so it performs well)
setlocal enableDelayedExpansion
set "dv==::"
if defined !dv! (
echo has NOT admin permissions
) else (
echo has admin permissions
)
If you want use this directly through command line ,but not from a batch file you can use:
set ^"|find "::"||echo has admin permissions
The TableModel
behind the JTable handles all of the data behind the table. In order to add and remove rows from a table, you need to use a DefaultTableModel
To create the table with this model:
JTable table = new JTable(new DefaultTableModel(new Object[]{"Column1", "Column2"}));
To add a row:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});
You can also remove rows with this method.
Full details on the DefaultTableModel can be found here
A way to find out old download links is to use internet archive tools like "Way back machine", https://archive.org/web/. You can browse older web pages versions and get the links you want.
For example, I needed to download the NDK rev 9, so I used this tool to access the NDK download page (https://developer.android.com/tools/sdk/ndk/) from March and the download link in March pointed to NDK rev 9.
In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.
//on ubuntu server
sudo /etc/init.d/mysql start
To avoid MySQL stop problem, you can use the "initctl" utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with "initctl" utility with stop and start operations.
$ sudo initctl stop mysql
$ sudo initctl start mysql
To verify the working, you can check the status of the service and get the process id (pid), simulate a failure by killing the "mysql" process and verify its status as running with new process id after sometime (typically within 1 minute) using the following commands.
$ sudo initctl status mysql # get pid
$ sudo kill -9 <pid> # kill mysql process
$ sudo initctl status mysql # verify status as running after sometime
Note : In latest Ubuntu version now initctl is replaced by systemctl