The one and probably not so good way of achieving your goal would using global variables.
You could achieve that by adding global $myArr;
to the beginning of your function.
However note that using global variables is in most cases a bad idea and probably avoidable.
The much better way would be passing your array as an argument to your function:
function someFuntion($arr){
$myVal = //some processing here to determine value of $myVal
$arr[] = $myVal;
return $arr;
}
$myArr = someFunction($myArr);
In Java
Below code calculates leap year count between two given year. Determine starting and ending point of the loop.
Then if parameter modulo 4 is equal 0 and parameter modulo 100 not equal 0 or parameter modulo 400 equal zero then it is leap year and increase counter.
static int calculateLeapYearCount(int year, int startingYear) {
int min = Math.min(year, startingYear);
int max = Math.max(year, startingYear);
int counter = 0;
for (int i = min; i < max; i++) {
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {
counter = counter + 1;
}
}
return counter;
}
Here's a solution that does not require any libraries.
This routine transmits every file in the directory d:/data/mpf10
to urlToConnect
String boundary = Long.toHexString(System.currentTimeMillis());
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
File dir = new File("d:/data/mpf10");
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
continue;
}
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
writer.println(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
}
writer.println("--" + boundary + "--");
} finally {
if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
// Handle response
I wrote a simple library for manipulating the JavaScript date object. You can try this:
var dateString = timeSolver.getString(new Date(), "YYYY/MM/DD HH:MM:SS.SSS")
Library here: https://github.com/sean1093/timeSolver
MAKE SIMPLE
const objects = [
{
"foo" : "bar",
"bar" : "sit",
"date":"2020-12-20"
},
{
"foo" : "lorem",
"bar" : "ipsum",
"date":"2018-07-02"
},
{
"foo" : "dolor",
"bar" : "amet",
"date":"2003-10-08"
},
{
"foo" : "lolor",
"bar" : "amet",
"date":"2003-10-08"
}
];
const filter = objects.filter(item => {
const obj = Object.values(item)
return obj.join("").indexOf('2003') !== -1
})
console.log(filter)
String[] split = data.split("\\|",-1);
This is not the actual requirement in all the time. The Drawback of above is show below:
Scenerio 1:
When all data are present:
String data = "5|6|7||8|9|10|";
String[] split = data.split("\\|");
String[] splt = data.split("\\|",-1);
System.out.println(split.length); //output: 7
System.out.println(splt.length); //output: 8
When data is missing:
Scenerio 2: Data Missing
String data = "5|6|7||8|||";
String[] split = data.split("\\|");
String[] splt = data.split("\\|",-1);
System.out.println(split.length); //output: 5
System.out.println(splt.length); //output: 8
Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.
String data = "5|6|7||8|||";
String[] split = data.split("\\|");
String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
System.out.println(split.length); //output: 5
System.out.println(splt.length); //output:7
What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.
Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require()
, do not work in the browser.
See browserify or webpack if you wish to serve browser-specific modules from Node.
If installed as an admin, use:-
uname - admin
pw - the passkey that was generated during installation
This way might makes more sense if you don't want to use str methods
int first = 1;
for (int i = 10; i < number; i *= 10) {
first = number / i;
}
If you want to do this programmatically (no manual text entry with gedit) here's a version for a Dockerfile based on user1341296's answer above:
FROM spittet/ruby-mysql
MAINTAINER [email protected]
RUN cp -R -p /var/lib/mysql /dev/shm && \
rm -rf /var/lib/mysql && \
sed -i -e 's,/var/lib/mysql,/dev/shm/mysql,g' /etc/mysql/my.cnf && \
/etc/init.d/mysql restart
Available on Docker hub here: https://hub.docker.com/r/richardjecooke/ruby-mysql-in-memory/
See man gcc
under Warning Options. There you have a whole bunch of unused
Warning Options
... -Wunused -Wunused-function -Wunused-label -Wunused-parameter -Wunused-value -Wunused-variable -Wunused-but-set-parameter -Wunused-but-set-variable
If you prefix any of them with no-
, it will disable this warning.
Many options have long names starting with -f or with -W---for example, -fmove-loop-invariants, -Wformat and so on. Most of these have both positive and negative forms; the negative form of -ffoo would be -fno-foo. This manual documents only one of these two forms, whichever one is not the default.
More detailed explanation can be found at Options to Request or Suppress Warnings
Use table-layout:fixed
in the table and word-wrap:break-word
in the td.
See this example:
<html>
<head>
<style>
table {border-collapse:collapse; table-layout:fixed; width:310px;}
table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
</style>
</head>
<body>
<table>
<tr>
<td>1</td>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>
</tr>
<tr>
<td>2</td>
<td>LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknown</td>
<td>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>
</tr>
<tr>
<td>3</td>
<td></td>
<td>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna...</td>
</tr>
</table>
</body>
</html>
table {border-collapse:collapse; table-layout:fixed; width:310px;}_x000D_
table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>Lorem Ipsum</td>_x000D_
<td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td>_x000D_
<td>LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknown</td>_x000D_
<td>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td></td>_x000D_
<td>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna...</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
I believe you have to reference bootstrap.js before bootstrap-datepicker.js
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
Below is an image showing nested frames and the effect of different target values, followed by an explanation of the image.
Imagine a webpage containing 3 nested <iframe>
aka "frame"/"frameset". So:
Then target attributes have these effects:
target="_self"
, the link targets frame 1 (i.e. the link targets the frame containing the link (i.e. targets itself))target="_parent"
, the link targets frame 2 (i.e. the link targets the parent frame)target="_top"
, the link targets the initial webpage (i.e. the link targets the topmost/outermost frame; (in this case; the link skips past the grandparent frame 3))
target="_top"
, the link also targets the initial webpage (i.e. again, the link targets the topmost/outermost frame)target="_blank"
, the link targets an auxiliary browsing context, aka a "new window"/"new tab"
target="_blank"
; use the rel="noopener"
attributeThe problem is what happens when you get NumberFormatexception
thrown? You print it and return nothing.
Note: You don't need to catch and throw an Exception back. Usually it is done to wrap it or print stack trace and ignore for example.
catch(RangeException e) {
throw e;
}
Try this function...
function calculate_age(birth_month,birth_day,birth_year)
{
today_date = new Date();
today_year = today_date.getFullYear();
today_month = today_date.getMonth();
today_day = today_date.getDate();
age = today_year - birth_year;
if ( today_month < (birth_month - 1))
{
age--;
}
if (((birth_month - 1) == today_month) && (today_day < birth_day))
{
age--;
}
return age;
}
OR
function getAge(dateString)
{
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
{
age--;
}
return age;
}
use string format :
birth = 5.25487
print(f'''
{birth}
''')
in the Kotlin you can do this simply: all you need is to create a static variable like this:
companion object {
var last_position = 0
}
then in your onBindViewHolder add this code:
holder.item.setOnClickListener{
holder.item.setBackgroundResource(R.drawable.selected_item)
notifyItemChanged(last_position)
last_position=position
}
which item is the child of recyclerView which you want to change its background after clicking on it.
You could write your own by looking at the JPEG format.
That said, try a pre-existing library like CImg, or Boost's GIL. Or for strictly JPEG's, libjpeg. There is also the CxImage class on CodeProject.
Here's a big list.
We can use angular pipe json
{{ jsonObject | json }}
for xampp vm on MacOS capitan, high sierra, MacOS Mojave (10.12+), you can follow these
1. mount /opt/lampp
2. explore the folder
3. open terminal from the folder
4. cd to `htdocs`>yourapp (ex: techaz.co)
5. vim .htaccess
6. paste your .htaccess content (that is suggested on options-permalink.php)
Your project needs to reference assembly System.Web.dll
. Server is an object of type HttpServerUtility
. Example:
HttpContext.Current.Server.MapPath(path);
Well I encountered a similar problem. The problem for me is that the JS file get loaded before the DOM render happens. So move your <script>
to the end of <body>
tag.
or use defer.
<script defer src="">
so rest assured e.preventDefault()
should work.
<p>tetxetextex</p>
<ol><li>first element</li></ol>
<p>other textetxeettx</p>
Because both <p>
and <ol>
are element rendered as block.
just set the following code in view will appear.
if ([[[UIDevice currentDevice] systemVersion] floatValue]<= 7) {
self.edgesForExtendedLayout = UIRectEdgeNone;
}
Without looping
I am using this if I simply want to strip the extension from a filename or variable (without listing any directories or existing files):
for %%f in ("%filename%") do set filename=%%~nf
If you want to strip the extension from a full path, use %%dpnf
instead:
for %%f in ("%path%") do set path=%%~dpnf
Example:
(Use directly in the console)
@for %f in ("file name.dat") do @echo %~nf
@for %f in ("C:\Dir\file.dat") do @echo %~dpnf
OUTPUT:
file name
C:\Dir\file
You have to store the timer id of the interval when you start it, you will use this value later to stop it, using the clearInterval
function:
$(function () {
var timerId = 0;
$('textarea').focus(function () {
timerId = setInterval(function () {
// interval function body
}, 1000);
});
$('textarea').blur(function () {
clearInterval(timerId);
});
});
Just piling on... similar to Feiyu Zhou's post. Here I'm adding the machine name.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
var env = context.HostingEnvironment;
var hostname = Environment.MachineName;
builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostname}.json", optional: true, reloadOnChange: true);
builder.AddEnvironmentVariables();
if (args != null)
{
builder.AddCommandLine(args);
}
})
.UseStartup<Startup>();
}
In my case the issue was caused by the JDK version. To solve this I suggest to go into your pom file and check the <jdk.version>1.7</jdk.version>.
Afterwards check java version in your cmd(windows) or terminal ( OSX or LINUX ) by typing : java -version.
Compare the version shown in the terminal\command prompt with what you have in your pom file. Make sure they are the same. Then run your project again.
const int * ptr;
means that the pointed data is constant and immutable but the pointer is not.
int * const ptr;
means that the pointer is constant and immutable but the pointed data is not.
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
warnings are output via stderr and the simple solution is to append '2> /dev/null' to the CLI. this makes a lot of sense to many users such as those with centos 6 that are stuck with python 2.6 dependencies (like yum) and various modules are being pushed to the edge of extinction in their coverage.
this is especially true for cryptography involving SNI et cetera. one can update 2.6 for HTTPS handling using the proc at: https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl-py2
the warning is still in place, but everything you want is back-ported. the re-direct of stderr will leave you with clean terminal/shell output although the stdout content itself does not change.
responding to FriendFX. sentence one (1) responds directly to the problem with an universal solution. sentence two (2) takes into account the cited anchor re 'disable warnings' which is python 2.6 specific and notes that RHEL/centos 6 users cannot directly do without 2.6. although no specific warnings were cited, para two (2) answers the 2.6 question I most frequently get re the short-comings in the cryptography module and how one can "modernize" (i.e., upgrade, backport, fix) python's HTTPS/TLS performance. para three (3) merely explains the outcome of using the re-direct and upgrading the module/dependencies.
The function str_squish()
from package stringr
of tidyverse does the magic!
library(dplyr)
library(stringr)
df <- data.frame(a = c(" aZe aze s", "wxc s aze "),
b = c(" 12 12 ", "34e e4 "),
stringsAsFactors = FALSE)
df <- df %>%
rowwise() %>%
mutate_all(funs(str_squish(.))) %>%
ungroup()
df
# A tibble: 2 x 2
a b
<chr> <chr>
1 aZe aze s 12 12
2 wxc s aze 34e e4
Due to https://mywiki.wooledge.org/BashPitfalls#Non-atomic_writes_with_xargs_-P (output from parallel jobs in xargs
risks being mixed), I would use GNU Parallel instead of xargs
to parallelize:
cat url.lst |
parallel -P0 -q curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' > outfile
In this particular case it may be safe to use xargs
because the output is so short, so the problem with using xargs
is rather that if someone later changes the code to do something bigger, it will no longer be safe. Or if someone reads this question and thinks he can replace curl
with something else, then that may also not be safe.
Try something like this
PdfPCell cell;
PdfPTable tableHeader;
PdfPTable tmpTable;
PdfPTable table = new PdfPTable(10) { WidthPercentage = 100, RunDirection = PdfWriter.RUN_DIRECTION_LTR, ExtendLastRow = false };
// row 1 / cell 1 (merge)
PdfPCell _c = new PdfPCell(new Phrase("SER. No")) { Rotation = -90, VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1 };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 2
_c = new PdfPCell(new Phrase("TYPE OF SHIPPING")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 3
_c = new PdfPCell(new Phrase("ORDER NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 4
_c = new PdfPCell(new Phrase("QTY.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 5
_c = new PdfPCell(new Phrase("DISCHARGE PPORT")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 6 (merge)
_c = new PdfPCell(new Phrase("DESCRIPTION OF GOODS")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 7
_c = new PdfPCell(new Phrase("LINE DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 8 (merge)
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 9 (merge)
_c = new PdfPCell(new Phrase("CLEARANCE DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 10 (merge)
_c = new PdfPCell(new Phrase("CUSTOM PERMIT NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 2 / cell 2
_c = new PdfPCell(new Phrase("AWB / BL NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 3
_c = new PdfPCell(new Phrase("COMPLEX NAME")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 4
_c = new PdfPCell(new Phrase("G.W Kgs.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 5
_c = new PdfPCell(new Phrase("DESTINATON")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 7
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
_doc.Add(table);
///////////////////////////////////////////////////////////
_doc.Close();
You might need to re-adjust slightly on the widths and borders but that is a one shot to do.
This will remove any number of blank lines
CTRL + H to replace
Select Extended search mode
replace all \r\n
with (space)
then switch to regular expression and replace all \s+
with \n
If you are behind a proxy, the following might be useful:
adb shell settings put global global_http_proxy_port YOUR_PROXY_PORT
adb shell settings put global global_http_proxy_host YOUR_PROXY_IP
reboot
This method take String as a argument and return the Character Array
/**
* @param sourceString
* :String as argument
* @return CharcterArray
*/
public static Character[] toCharacterArray(String sourceString) {
char[] charArrays = new char[sourceString.length()];
charArrays = sourceString.toCharArray();
Character[] characterArray = new Character[charArrays.length];
for (int i = 0; i < charArrays.length; i++) {
characterArray[i] = charArrays[i];
}
return characterArray;
}
Adding a service reference allows you to create a WCF client, which can be used to talk to a regular web service provided you use the appropriate binding. Adding a web reference will allow you to create only a web service (i.e., SOAP) reference.
If you are absolutely certain you are not ready for WCF (really don't know why) then you should create a regular web service reference.
Project Properties -> Compiler Tab -> Advanced Compile Options button
Project Properties -> Application Tab
An HttpOnly
cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly
attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly
.
Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly
by just XSS and still have access to the cookie via JS and thus make the HttpOnly
on your cookie completely useless.
I recently (today) needed to figure out a quick way to do this and of course I was going to use the exception approach for ease when the monkey on the shoulder (conscience) woke up so it took me down this old familiar rabbit hole; no exceptions are not that much more expensive in fact sometimes exceptions are faster (old AIX multiprocessor systems) but regardless it’s to elegant so I did something that the younger me never did and to my amazement nobody here did either (apologize if someone did and I missed it I honestly did not find) : so what did I think we all missed; taking a look at how the JRE implemented it, yes they threw an exception but we can always skip that part.
The younger me from 10 years ago would have felt this to be beneath him, but then again he is a loud mouthed show off with a poor temperament and a god complex so there is that.
I am putting this here for the benefit of anyone coming here in the future. Here is what I found:
public static int parseInt(String s, int radix) throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
In Angular 7.X
The CSS classes are updated as follows, depending on the type of the expression evaluation:
string - the CSS classes listed in the string (space delimited) are added
Array - the CSS classes declared as Array elements are added
Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.
<some-element [ngClass]="'first second'">...</some-element>
<some-element [ngClass]="['first', 'second']">...</some-element>
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
Try writing the following batch file and executing it:
Echo one
cmd
Echo two
cmd
Echo three
cmd
Only the first two lines get executed. But if you type "exit" at the command prompt, the next two lines are processed. It's a shell loading another.
To be sure that this is not what is happening in your script, just type "exit" when the first command ends.
HTH!
I managed to solve this in the Request handling code following advice from 'monsur'.
string origin = WebOperationContext.Current.IncomingRequest.Headers.Get("Origin");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", origin);
For Python 3.2 scripts, the only choice is cx_Freeze. Build it from sources; otherwise it won't work.
For Python 2.x I suggest PyInstaller as it can package a Python program in a single executable, unlike cx_Freeze which outputs also libraries.
You could do something like this:
<body>
<textarea id="txtArea" onkeypress="onTestChange();"></textarea>
<script>
function onTestChange() {
var key = window.event.keyCode;
// If the user has pressed enter
if (key === 13) {
document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
return false;
}
else {
return true;
}
}
</script>
</body>
Although the new line character feed from pressing enter will still be there, but its a start to getting what you want.
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
Whenever you have seen coding from open source community like Guava and from Google Developer (Android Library) they used this approach
List<String> strings = new ArrayList<String>();
because it's hide the implementation detail from user. You precisely
List<String> strings = new ArrayList<String>();
it's generic approach and this specialized approach
ArrayList<String> strings = new ArrayList<String>();
For Reference: Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces
This is a simple function (Bash shell) which lets you create a directory if it doesn't exist.
#----------------------------------
# Create a directory if it doesn't exist
#------------------------------------
createDirectory() {
if [ ! -d $1 ]
then
mkdir -p $1
fi
}
You can call the above function as:
createDirectory /tmp/fooDir/BarDir
The above creates fooDir and BarDir if they don't exist. Note the "-p" option in the mkdir command which creates directories recursively.
Looper allows tasks to be executed sequentially on a single thread. And handler defines those tasks that we need to be executed. It is a typical scenario that I am trying to illustrate in this example:
class SampleLooper extends Thread {
@Override
public void run() {
try {
// preparing a looper on current thread
// the current thread is being detected implicitly
Looper.prepare();
// now, the handler will automatically bind to the
// Looper that is attached to the current thread
// You don't need to specify the Looper explicitly
handler = new Handler();
// After the following line the thread will start
// running the message loop and will not normally
// exit the loop unless a problem happens or you
// quit() the looper (see below)
Looper.loop();
} catch (Throwable t) {
Log.e(TAG, "halted due to an error", t);
}
}
}
Now we can use the handler in some other threads(say ui thread) to post the task on Looper to execute.
handler.post(new Runnable()
{
public void run() {
//This will be executed on thread using Looper.
}
});
On UI thread we have an implicit Looper that allow us to handle the messages on ui thread.
try this
provider = new CultureInfo("en-US");
DateTime.ParseExact("9/1/2009", "M/d/yyyy", provider);
Bye.
The Error
constructor is used to create an error object. Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.
User-defined Errors are thrown via the throw
statement. program control will be passed to the first catch
block in the call stack.
The difference between throwing an error with and without Error object:
throw {'hehe':'haha'};
In chrome devtools looks like this:
Chrome tells us that we have an uncaught error which just is a JS object. The object itself could have information regarding the error but we still don't know immediately where it came from. Not very useful when we are working on our code and debugging it.
throw new Error({'hehe':'haha'});
In chrome devtools looks like this:
An error thrown with the Error object gives us a stack trace when we expand it. This gives us valuable information where the error precisely came from which is often valuable information when debugging your code. Further note that the error says [object Object]
, this is because the Error
constructor expects a message string as a first argument. When it receives a object it will coerce it into a string.
Process.env does not change, so it must not be used for accessing per-request environment variables whose values may change on a per-request basis. So, if the user spawns an application process, but not as part of handling a request, then that application process will not have per-request environment variables stored inside OS-level environment variables. So, use this code to store process env and your program run successfully.
const port = process.env.PORT || 2000;
app.listen(port,()=>{
console.log("Server running at port 2000");
})
$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');
os.path.splitext() won't work if there are multiple dots in the extension.
For example, images.tar.gz
>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> print os.path.splitext(file_name)[0]
images.tar
You can just find the index of the first dot in the basename and then slice the basename to get just the filename without extension.
>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> index_of_dot = file_name.index('.')
>>> file_name_without_extension = file_name[:index_of_dot]
>>> print file_name_without_extension
images
Declare the parameter in test.ps1:
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$input_dir,
[Parameter(Mandatory=$True)]
[string]$output_dir,
[switch]$force = $false
)
Run the script from Run OR Windows Task Scheduler:
powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"
or,
powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"
In addition if one uses static keyword on a variable like this example:
namespace {
static int flag;
}
It would not be seen in the mapping file
Take a look at this.
Change your query to:
SET @rank=0;
SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC;
SELECT @rank;
The last select is your count.
I found same question or related question on stackoverflow
Is there any way to change input type=“date” format?
I found one simple solution, You can not give particulate Format but you can customize Like this.
HTML Code:
<body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>
CSS Code:
#dt{text-indent: -500px;height:25px; width:200px;}
Javascript Code :
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}
Output:
Set the auto increment field to NULL or 0 if you want it to be auto magically assigned...
You would never want to run that, but you may want to source it.
. ~/.bash_profile
source ~/.bash_profile
both should work. But this is an odd request, because that file should be sourced automatically when you start bash, unless you're explicitly starting it non-interactively. From the man page:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
The question didn't ask which is fastest, but to add to the sed answer, -n '1p' is badly performing as the pattern space is still scanned on large files. Out of curiosity I found that 'head' wins over sed narrowly:
# best:
head -n1 $bigfile >/dev/null
# a bit slower than head (I saw about 10% difference):
sed '1q' $bigfile >/dev/null
# VERY slow:
sed -n '1p' $bigfile >/dev/null
You need to save the access token to file or database as a json string during the initial authorization request, and set the access type to offline $client->setAccessType("offline")
Then, during subsequent api requests, grab the access token from your file or db and pass it to the client:
$accessToken = json_decode($row['token'], true);
$client->setAccessToken($accessToken);
Now you need to check if the token has expired:
if ($client->isAccessTokenExpired()) {
// access token has expired, use the refresh token to obtain a new one
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
// save the new token to file or db
// ...json_encode($client->getAccessToken())
The fetchAccessTokenWithRefreshToken()
function will do the work for you and provide a new access token, save it back to your file or database.
You can group conditions with parentheses. When you are checking if a field is equal to another, you want to use OR
. For example WHERE a='1' AND (b='123' OR b='234')
.
SELECT u.*
FROM rooms AS u
JOIN facilities_r AS fu
ON fu.id_uc = u.id_uc AND (fu.id_fu='4' OR fu.id_fu='3')
WHERE vizibility='1'
GROUP BY id_uc
ORDER BY u_premium desc, id_uc desc
For your current structure, you could also try the following:
select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country
I think I prefer a union between the two tables, and a group by on the country name as mentioned above.
But I would also recommend normalising your tables. Ideally you'd have a country table, with Id and Name, and a payments table with: CountryId (FK to countries), Total, Type (cash/cheque)
Just to reconcile the difference between sandeepmistry's answer and davidgyoung's answer:
02 01 1a 1a ff 4C 00
Is part of the advertising data format specification [1]
02 # length of following AD structure
01 # <<Flags>> AD Structure [2]
1a # read as b00011010.
# In this case, LE General Discoverable,
# and simultaneous BR/EDR but this may vary by device!
1a # length of following AD structure
FF # Manufacturer specific data [3]
4C00 # Apple Inc [4]
0215 # ?? some 2-byte header
Missing from the AD is a Service [5] definition. I think the iBeacon protocol itself has no relationship to the GATT and standard service discovery. If you download RedBearLab's iBeacon program, you'll see that they happen to use the GATT for configuring the advertisement parameters, but this seems to be specific to their implementation, and not part of the spec. The AirLocate program doesn't seem to use the GATT for configuration, for instance, according to LightBlue and or other similar programs I tried.
References:
I believe there is a simpler solution.
You must use Html.Hidden
instead of Html.HiddenFor
. Look:
@Html.Hidden("CRN", ViewData["crn"]);
This will create an INPUT
tag of type="hidden"
, with id="CRN"
and name="CRN"
, and the correct value inside the value
attribute.
Hope it helps!
A SOAP request is an XML file consisting of the parameters you are sending to the server.
The SOAP response is equally an XML file, but now with everything the service wants to give you.
Basically the WSDL is a XML file that explains the structure of those two XML.
To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
import javax.xml.soap.*;
public class SOAPClientSAAJ {
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
http://www.webservicex.net/uszip.asmx?op=GetInfoByCity
To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action
Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
String soapAction = "http://www.webserviceX.NET/GetInfoByCity";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "http://www.webserviceX.NET";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:GetInfoByCity>
<myNamespace:USCity>New York</myNamespace:USCity>
</myNamespace:GetInfoByCity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
soapBodyElem1.addTextNode("New York");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
}
&&
and ||
are what is called "short circuiting". That means that they will not evaluate the second operand if the first operand is enough to determine the value of the expression.
For example if the first operand to &&
is false then there is no point in evaluating the second operand, since it can't change the value of the expression (false && true
and false && false
are both false). The same goes for ||
when the first operand is true.
You can read more about this here: http://en.wikipedia.org/wiki/Short-circuit_evaluation From the table on that page you can see that &&
is equivalent to AndAlso
in VB.NET, which I assume you are referring to.
My approach is slightly different. I do not copy properties into new instances, I just change the prototype of existing POJOs (may not work well on older browsers). Each class is responsible for providing a SetPrototypes method to set the prototoypes of any child objects, which in turn provide their own SetPrototypes methods.
(I also use a _Type property to get the class name of unknown objects but that can be ignored here)
class ParentClass
{
public ID?: Guid;
public Child?: ChildClass;
public ListOfChildren?: ChildClass[];
/**
* Set the prototypes of all objects in the graph.
* Used for recursive prototype assignment on a graph via ObjectUtils.SetPrototypeOf.
* @param pojo Plain object received from API/JSON to be given the class prototype.
*/
private static SetPrototypes(pojo: ParentClass): void
{
ObjectUtils.SetPrototypeOf(pojo.Child, ChildClass);
ObjectUtils.SetPrototypeOfAll(pojo.ListOfChildren, ChildClass);
}
}
class ChildClass
{
public ID?: Guid;
public GrandChild?: GrandChildClass;
/**
* Set the prototypes of all objects in the graph.
* Used for recursive prototype assignment on a graph via ObjectUtils.SetPrototypeOf.
* @param pojo Plain object received from API/JSON to be given the class prototype.
*/
private static SetPrototypes(pojo: ChildClass): void
{
ObjectUtils.SetPrototypeOf(pojo.GrandChild, GrandChildClass);
}
}
Here is ObjectUtils.ts:
/**
* ClassType lets us specify arguments as class variables.
* (where ClassType == window[ClassName])
*/
type ClassType = { new(...args: any[]): any; };
/**
* The name of a class as opposed to the class itself.
* (where ClassType == window[ClassName])
*/
type ClassName = string & {};
abstract class ObjectUtils
{
/**
* Set the prototype of an object to the specified class.
*
* Does nothing if source or type are null.
* Throws an exception if type is not a known class type.
*
* If type has the SetPrototypes method then that is called on the source
* to perform recursive prototype assignment on an object graph.
*
* SetPrototypes is declared private on types because it should only be called
* by this method. It does not (and must not) set the prototype of the object
* itself - only the protoypes of child properties, otherwise it would cause a
* loop. Thus a public method would be misleading and not useful on its own.
*
* https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript
*/
public static SetPrototypeOf(source: any, type: ClassType | ClassName): any
{
let classType = (typeof type === "string") ? window[type] : type;
if (!source || !classType)
{
return source;
}
// Guard/contract utility
ExGuard.IsValid(classType.prototype, "type", <any>type);
if ((<any>Object).setPrototypeOf)
{
(<any>Object).setPrototypeOf(source, classType.prototype);
}
else if (source.__proto__)
{
source.__proto__ = classType.prototype.__proto__;
}
if (typeof classType["SetPrototypes"] === "function")
{
classType["SetPrototypes"](source);
}
return source;
}
/**
* Set the prototype of a list of objects to the specified class.
*
* Throws an exception if type is not a known class type.
*/
public static SetPrototypeOfAll(source: any[], type: ClassType): void
{
if (!source)
{
return;
}
for (var i = 0; i < source.length; i++)
{
this.SetPrototypeOf(source[i], type);
}
}
}
Usage:
let pojo = SomePlainOldJavascriptObjectReceivedViaAjax;
let parentObject = ObjectUtils.SetPrototypeOf(pojo, ParentClass);
// parentObject is now a proper ParentClass instance
Use this if you want to reset the select to the option which has the "selected" attribute. Works similar to the form.reset() inbuilt javascript function to the select.
$("#name").val($("#name option[selected]").val());
You can set data to session simply like this in Codeigniter:
$this->load->library('session');
$this->session->set_userdata(array(
'user_id' => $user->uid,
'username' => $user->username,
'groupid' => $user->groupid,
'date' => $user->date_cr,
'serial' => $user->serial,
'rec_id' => $user->rec_id,
'status' => TRUE
));
and you can get it like this:
$u_rec_id = $this->session->userdata('rec_id');
$serial = $this->session->userdata('serial');
What worked for me :
div#scrollable {
overflow-y: scroll;
max-height: 100vh;
}
instead of remove()
you can use exclude()
function to remove an object from the queryset.
it's syntax is similar to filter()
eg : -
qs = qs.exclude(id= 1)
in above code it removes all objects from qs with id '1'
additional info :-
filter()
used to select specific objects but exclude()
used to remove
Sometimes you have what appears to be a tuple with a leading underscore as in
def foo(bar):
return _('my_' + bar)
In this case, what's going on is that _() is an alias for a localization function that operates on text to put it into the proper language, etc. based on the locale. For example, Sphinx does this, and you'll find among the imports
from sphinx.locale import l_, _
and in sphinx.locale, _() is assigned as an alias of some localization function.
I think the problem may be in the charset that you are trying to use. It is probably best to use UTF-8 instead of iso-8859-1.
Also open whatever file is being used for your InputStream and make sure no special characters were accidentally inserted. Sometimes you have to specifically tell your editor to display hidden / special characters.
We can define the so-called foreign key
in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,
student
{
_id: ObjectId(...),
name: 'Jane',
courses: ['bio101', 'bio102'] // <= ids of the courses
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
The courses
field contains _id
s of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane
, we need to perform another operation to retrieve the course
document via _id
.
If the course bio101
is removed, we need to perform another operation to update the courses
field in the student
document.
The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:
Example:
student
{
name: 'Kate Monster',
addresses : [
{ street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
{ street: '123 Avenue Q', city: 'New York', cc: 'USA' }
]
}
Like the student
/course
example above.
Suitable for one-to-squillions, such as log messages.
host
{
_id : ObjectID('AAAB'),
name : 'goofy.example.com',
ipaddr : '127.66.66.66'
}
logmsg
{
time : ISODate("2014-03-28T09:42:41.382Z"),
message : 'cpu is on fire!',
host: ObjectID('AAAB') // Reference to the Host document
}
Virtually, a host
is the parent of a logmsg
. Referencing to the host
id saves much space given that the log messages are squillions.
References:
I am posting a way to use _netrc
to download materials from the site www.course.com.
If someone is going to use the coursera-dl to download the open-class materials on www.coursera.com, and on the Windows OS someone wants to use a file like ".netrc" which is in like-Unix OS to add the option -n
instead of -U <username> -P <password>
for convenience. He/she can do it like this:
Check the home path on Windows OS: setx HOME %USERPROFILE%
(refer to VonC's answer). It will save the HOME
environment variable as C:\Users\"username"
.
Locate into the directory C:\Users\"username"
and create a file name _netrc
.NOTE: there is NOT any suffix.
the content is like: machine coursera-dl login <user> password <pass>
Use a command like coursera-dl -n --path PATH <course name>
to download the class materials. More coursera-dl options details for this page.
The nextInt()
method leaves the \n
(end line) symbol and is picked up immediately by nextLine()
, skipping over the next input. What you want to do is use nextLine()
for everything, and parse it later:
String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int
This is by far the easiest way to avoid problems--don't mix your "next" methods. Use only nextLine()
and then parse int
s or separate words afterwards.
Also, make sure you use only one Scanner
if your are only using one terminal for input. That could be another reason for the exception.
Last note: compare a String
with the .equals()
function, not the ==
operator.
if (playAgain == "yes"); // Causes problems
if (playAgain.equals("yes")); // Works every time
Just insert a ' before anything to be inserted. It will be like a escape character in sqlServer
Example: When you have a field as, I'm fine. you can do: UPDATE my_table SET row ='I''m fine.';
When we have to send multiple trigger parameters to jenkins job, the following commands works.
curl -X POST -i -u "auto_user":"xxxauthentication_tokenxxx" "JENKINS_URL/view/tests/job/helloworld/buildWithParameters?param1=162¶m2=store"
Try this example
Html
<div class="testimonial" data-index="1">
Testimonial 1
</div>
<div class="testimonial" data-index="2">
Testimonial 2
</div>
<div class="testimonial" data-index="3">
Testimonial 3
</div>
<div class="testimonial" data-index="4">
Testimonial 4
</div>
<div class="testimonial" data-index="5">
Testimonial 5
</div>
When we want to access those divs
which has data-index
greater than 2
then we need this jquery.
$('div[class="testimonial"]').each(function(index,item){
if(parseInt($(item).data('index'))>2){
$(item).html('Testimonial '+(index+1)+' by each loop');
}
});
Use QString::arg()
for the same effect.
if you're not using the ->
format, you can do this:
$a = "SQL command...";
if ($b = mysqli_query($con,$a)) {
// results was successful
} else {
// result was not successful
}
var people =
[{"name": 'a75',"item1": "false","item2":"false"},
{"name": 'z32',"item1": "true","item2": "false"},
{"name": 'e77',"item1": "false","item2": "false"}];
function mycomparator(a,b) { return parseInt(a.name) - parseInt(b.name); }
people.sort(mycomparator);
something along the lines of this maybe (or as we used to say, this should work).
Step 1: Click on Create new File
Step 2: Enter the folder name that you want, then press /
Step 3: Enter a sample file name. You must enter some text.
Step 4: Click Commit new file to create the folder
Step 5: Your folder is created!
Improving the answer https://stackoverflow.com/a/14720445/6654512 to work with Python3. That piece of code would sometimes generate numbers greater than 1 and matplotlib would throw an error.
for X,Y in data:
scatter(X, Y, c=numpy.random.random(3))
You can also use weightSum
and layout_weight
property to adjust your different screen.
For that, you have to make android:layout_width
= 0dp,
and android:layout_width
= (whatever you want);
To increase the phpMyAdmin
Session Timeout, open config.inc.php
in the root phpMyAdmin
directory and add this setting (anywhere).
$cfg['LoginCookieValidity'] = <your_new_timeout>;
Where <your_new_timeout>
is some number larger than 1800.
Note:
Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.
Paste typically merges lines of multiple files, but it can also be used to convert individual lines of a file into a single line. The delimiter flag allows you to pass a x+x type equation to bc.
paste -s -d+ infile | bc
Alternatively, when piping from stdin,
<commands> | paste -s -d+ - | bc
Are you applying a RowFilter to your DefaultView later in the code? This could change the results returned.
I would also avoid using the string as the display member if you have a direct reference the the data column I would use the object properties:
mnuActionLanguage.ComboBox.DataSource = lTable.DefaultView;
mnuActionLanguage.ComboBox.DisplayMember = lName.ColumnName;
I have tried this with a blank form and standard combo, and seems to work for me.
1.Rename the old UDT,
2.Execute query ,
3.Drop the old UDT.
A little more compact than the other answers if you want to use c as a TForm:
if(c is TForm form){
form.DoStuff();
}
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]
NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
NSString* firstBit = [foo objectAtIndex: 0];
Update 7/3/2018:
Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:
let substrings = "10/04/2011".split(separator: "/")
let firstBit = substrings[0]
Although note that it gives you an array of Substring
. If you need to convert these back to ordinary strings, use map
let strings = "10/04/2011".split(separator: "/").map{ String($0) }
let firstBit = strings[0]
or
let firstBit = String(substrings[0])
in a Microsoft SQL Server you can use this:
declare @sql2 nvarchar(2000)
set @sql2 ='
use ?
if ( db_name(db_id()) not in (''master'',''tempdb'',''model'',''msdb'',''SSISDB'') )
begin
select
db_name() as db,
SS.name as schemaname,
SO.name tablename,
SC.name columnname,
ST.name type,
case when ST.name in (''nvarchar'', ''nchar'')
then convert(varchar(10), ( SC.max_length / 2 ))
when ST.name in (''char'', ''varchar'')
then convert(varchar(10), SC.max_length)
else null
end as length,
case when SC.is_nullable = 0 then ''No'' when SC.is_nullable = 1 then ''Yes'' else null end as nullable,
isnull(SC.column_id,0) as col_number
from sys.objects SO
join sys.schemas SS
on SS.schema_id = SO.schema_id
join sys.columns SC
on SO.object_id = SC.object_id
left join sys.types ST
on SC.user_type_id = ST.user_type_id and SC.system_type_id = ST.system_type_id
where SO.is_ms_shipped = 0
end
'
exec sp_msforeachdb @command1 = @sql2
this shows you all tables and columns ( and their definition ) from all userdefined databases.
Highlighting with your mouse only highlights characters on the terminal. VI doesn't really get this information, so you have to highlight differently.
Press 'v' to enter a select mode, and use arrow keys to move that around. To delete, press x. To select lines at a time, press shift+v. To select blocks, try ctrl+v. That's good for, say, inserting lots of comment lines in front of your code :).
I'm OK with VI, but it took me a while to improve. My work mates recommended me this cheat sheet. I keep a printout on the wall for those odd moments when I forget something.
Happy hacking!
I used below code and it's working fine for me. :
let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
do {
dictonary = try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
if let myDictionary = dictonary
{
print(" User name is: \(myDictionary["userName"]!)")
}
} catch let error as NSError {
print(error)
}
}
In an instance where you want to set a placeholder and not have a default value be selected, you can use this option.
<select defaultValue={'DEFAULT'} >
<option value="DEFAULT" disabled>Choose a salutation ...</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Miss</option>
<option value="5">Dr</option>
</select>
Here the user is forced to pick an option!
EDIT
If this is a controlled component
In this case unfortunately you will have to use both defaultValue and value violating React a bit. This is because react by semantics does not allow setting a disabled value as active.
function TheSelectComponent(props){
let currentValue = props.curentValue || "DEFAULT";
return(
<select value={currentValue} defaultValue={'DEFAULT'} onChange={props.onChange}>
<option value="DEFAULT" disabled>Choose a salutation ...</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Miss</option>
<option value="5">Dr</option>
</select>
)
}
Okay... so i know that i'm answering to a decade question, but wanted to add something! I wanted to add a google calendar with special iframe parameters. Problem is that the calendar didn't work without it. 30 seconds is a bit short for my use, so i changed that in my own file to 15 minutes This worked for me.
<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
document.getElementById("calendar").src=calendar.src;
}
</script>
<iframe id="calendar" src="[URL]" style="border-width:0" width=100% height=100% frameborder="0" scrolling="no"></iframe>
At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:
CKEDITOR.on("instanceCreated", function(event) {
event.editor.on("change", function () {
$("#trackingDiv").html(event.editor.getData());
});
});
I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.
Alright, so I got it working by changing this
log4j.rootLogger=DebugAppender
to this
log4j.rootLogger=DEBUG, DebugAppender
Apparently you have to specify the logging level to the rootLogger
first? I apologize if I wasted anyone's time.
Also, I decided to answer my own question because this wasn't a classpath issue.
pip
is designed to upgrade python packages and not to upgrade python itself. pip
shouldn't try to upgrade python when you ask it to do so.
Don't type pip install python
but use an installer instead.
git push
doesn't push all of your local branches: how would it know which remote branches to push them to? It only pushes local branches which have been configured to push to a particular remote branch.
On my version of Git (1.6.5.3), when I run git remote show origin
it actually prints out which branches are configured for push:
Local refs configured for 'git push':
master pushes to master (up to date)
quux pushes to quux (fast forwardable)
Q. But I could push to master
without worrying about all this!
When you git clone
, by default it sets up your local master
branch to push to the remote's master
branch (locally referred to as origin/master
), so if you only commit on master
, then a simple git push
will always push your changes back.
However, from the output snippet you posted, you're on a branch called develop
, which I'm guessing hasn't been set up to push to anything. So git push
without arguments won't push commits on that branch.
When it says "Everything up-to-date", it means "all the branches you've told me how to push are up to date".
Q. So how can I push my commits?
If what you want to do is put your changes from develop
into origin/master
, then you should probably merge them into your local master
then push that:
git checkout master
git merge develop
git push # will push 'master'
If what you want is to create a develop
branch on the remote, separate from master
, then supply arguments to git push
:
git push origin develop
That will: create a new branch on the remote called develop
; and bring that branch up to date with your local develop
branch; and set develop
to push to origin/develop
so that in future, git push
without arguments will push develop
automatically.
If you want to push your local develop
to a remote branch called something other than develop
, then you can say:
git push origin develop:something-else
However, that form won't set up develop
to always push to origin/something-else
in future; it's a one-shot operation.
This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.
Example: Suppose you defined in the REST definition
@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")
Then during the definition of the function, it should be
public ResponseEntity<List> getData(@PathVariable String appId)
This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:
public ResponseEntity<List> getData(@PathVariable String ID)
Are you explicitly setting the values as blank? For example:
<input type="text" name="textfield" value="">
That should stop browsers putting data in where it shouldn't. Alternatively, you can add the autocomplete
attribute to the form tag:
<form autocomplete="off" ...></form>
If you don't care about the compatibility with older IE versions (< 8), you could make a custom jQuery plugin and then call it on the overflowing element.
This solution has an advantage over the one Šime Vidas proposed, as it doesn't overwrite the scrolling behavior - it just blocks it when appropriate.
$.fn.isolatedScroll = function() {
this.bind('mousewheel DOMMouseScroll', function (e) {
var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail,
bottomOverflow = this.scrollTop + $(this).outerHeight() - this.scrollHeight >= 0,
topOverflow = this.scrollTop <= 0;
if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
e.preventDefault();
}
});
return this;
};
$('.scrollable').isolatedScroll();
This what I came up with, since I need to run several operations in a chain.
<button onclick="tprom('Hello Niclas')">test promise</button>
<script>
function tprom(mess) {
console.clear();
var promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(mess);
}, 2000);
});
var promise2 = new Promise(async function (resolve, reject) {
await promise;
setTimeout(function () {
resolve(mess + ' ' + mess);
}, 2000);
});
var promise3 = new Promise(async function (resolve, reject) {
await promise2;
setTimeout(function () {
resolve(mess + ' ' + mess+ ' ' + mess);
}, 2000);
});
promise.then(function (data) {
console.log(data);
});
promise2.then(function (data) {
console.log(data);
});
promise3.then(function (data) {
console.log(data);
});
}
</script>
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
in intelliJ IDEA go-lang plugin (and i assume in jetbrains Gogland) you can just set the test kind to file under run > edit configurations
not mysqldump, but mysql cli...
mysql -e "select * from myTable" -u myuser -pxxxxxxxxx mydatabase
you can redirect it out to a file if you want :
mysql -e "select * from myTable" -u myuser -pxxxxxxxx mydatabase > mydumpfile.txt
Update: Original post asked if he could dump from the database by query. What he asked and what he meant were different. He really wanted to just mysqldump all tables.
mysqldump --tables myTable --where="id < 1000"
gitfox
is a tool to execute command on all subrepos
npm install gitfox -g
g pull
Extension for UISegmentedControl
for setting Font Size.
extension UISegmentedControl {
@available(iOS 8.2, *)
func setFontSize(fontSize: CGFloat) {
let normalTextAttributes: [NSObject : AnyObject]!
if #available(iOS 9.0, *) {
normalTextAttributes = [
NSFontAttributeName: UIFont.monospacedDigitSystemFontOfSize(fontSize, weight: UIFontWeightRegular)
]
} else {
normalTextAttributes = [
NSFontAttributeName: UIFont.systemFontOfSize(fontSize, weight: UIFontWeightRegular)
]
}
self.setTitleTextAttributes(normalTextAttributes, forState: .Normal)
}
}
It's quite simple.
All you need to do is:
Might be a pasting problem, but as far as I can see from your code, you're missing the single quotes around the HTML part you're echo-ing.
If not, could you post the code correctly and tell us what line is causing the error?
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
The basic one, ask tasklist to filter its output and only show the indicated process id information
tasklist /fi "pid eq 4444"
To only get the process name, the line must be splitted
for /f "delims=," %%a in ('
tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a
In this case, the list of processes is retrieved without headers (/nh
) in csv format (/fo:csv
). The commas are used as token delimiters and the first token in the line is the image name
note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command
for /f "delims=," %%a in ('
tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a
This will generate the task list and filter it searching for the process id in the second column of the csv output.
edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.
tasklist /fi "idp eq 4444"
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
In Android Q (Android 10) you can't enable/disable wifi programmatically anymore. Use Settings Panel to toggle wifi connectivity:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
startActivityForResult(panelIntent, 0)
} else {
// use previous solution, add appropriate permissions to AndroidManifest file (see answers above)
(this.context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }
}
Here is a solution using Streams with Java 8
// lets assume the original list is filled with {1,1,2,3,6,3,8,7}
List<String> original = new ArrayList<>();
List<String> result = new ArrayList<>();
You just look if the frequency of this object is more than once in your list. Then call .distinct() to only have unique elements in your result
result = original.stream()
.filter(e -> Collections.frequency(original, e) > 1)
.distinct()
.collect(Collectors.toList());
// returns {1,3}
// returns only numbers which occur more than once
result = original.stream()
.filter(e -> Collections.frequency(original, e) == 1)
.collect(Collectors.toList());
// returns {2,6,8,7}
// returns numbers which occur only once
result = original.stream()
.distinct()
.collect(Collectors.toList());
// returns {1,2,3,6,8,7}
// returns the list without duplicates
For example,
package main
import "fmt"
func main() {
s := "abc"
var a [20]byte
copy(a[:], s)
fmt.Println("s:", []byte(s), "a:", a)
}
Output:
s: [97 98 99] a: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
Well I have used the following sample query in my SQL 2000 database, it works well for SQL 2005 too. The power it gives you is dynamically order by using multiple columns. I tell you ... this is powerful :)
ALTER PROCEDURE [dbo].[RE_ListingReports_SelectSummary]
@CompanyID int,
@pageNumber int,
@pageSize int,
@sort varchar(200)
AS
DECLARE @sql nvarchar(4000)
DECLARE @strPageSize nvarchar(20)
DECLARE @strSkippedRows nvarchar(20)
DECLARE @strFields nvarchar(4000)
DECLARE @strFilter nvarchar(4000)
DECLARE @sortBy nvarchar(4000)
DECLARE @strFrom nvarchar(4000)
DECLARE @strID nvarchar(100)
If(@pageNumber < 0)
SET @pageNumber = 1
SET @strPageSize = CAST(@pageSize AS varchar(20))
SET @strSkippedRows = CAST(((@pageNumber - 1) * @pageSize) AS varchar(20))-- For example if pageNumber is 5 pageSize is 10, then SkippedRows = 40.
SET @strID = 'ListingDbID'
SET @strFields = 'ListingDbID,
ListingID,
[ExtraRoom]
'
SET @strFrom = ' vwListingSummary '
SET @strFilter = ' WHERE
CompanyID = ' + CAST(@CompanyID As varchar(20))
End
SET @sortBy = ''
if(len(ltrim(rtrim(@sort))) > 0)
SET @sortBy = ' Order By ' + @sort
-- Total Rows Count
SET @sql = 'SELECT Count(' + @strID + ') FROM ' + @strFROM + @strFilter
EXEC sp_executesql @sql
--// This technique is used in a Single Table pagination
SET @sql = 'SELECT ' + @strFields + ' FROM ' + @strFROM +
' WHERE ' + @strID + ' IN ' +
' (SELECT TOP ' + @strPageSize + ' ' + @strID + ' FROM ' + @strFROM + @strFilter +
' AND ' + @strID + ' NOT IN ' + '
(SELECT TOP ' + @strSkippedRows + ' ' + @strID + ' FROM ' + @strFROM + @strFilter + @SortBy + ') '
+ @SortBy + ') ' + @SortBy
Print @sql
EXEC sp_executesql @sql
The best part is sp_executesql caches later calls, provided you pass same parameters i.e generate same sql text.
Some examples:
1 << 4
equal to 2^4
i.e. 16)1 << 4
or 1 << 5
is more readable.(Firstly read the other answers which has explained the for
in the <label></label>
tags.
Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1"
but with different ids id="r1_1" ... id="r1_2"
So this way the answer is more clear and removes the conflicts between name and ids as well.
You need different ids for different options of the radio box.
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
<label for="r1_1">button text one</label>_x000D_
<br/>_x000D_
<input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
<label for="r1_2">button text two</label>_x000D_
<br/>_x000D_
<input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
<label for="r1_3">button text three</label>
_x000D_
The Python approach to "main" is almost unique to the language(*).
The semantics are a bit subtle. The __name__
identifier is bound to the name of any module as it's being imported. However, when a file is being executed then __name__
is set to "__main__"
(the literal string: __main__
).
This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:
#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
pass
def some_function(*args,**kwargs):
pass
if __name__ == '__main__':
print("This only executes when %s is executed rather than imported" % __file__)
Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.
It's important to understand that all of the code above the if __name__
line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a print
statement before the if __name__
line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).
I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.
Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__"
to isolate a block of code which calls a suite of unit tests that apply to this module.
(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).
Summary: if __name__ == '__main__':
has two primary use cases:
It's fairly common to def main(*args)
and have if __name__ == '__main__':
simply call main(*sys.argv[1:])
if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module()
and calling test_module()
in your if __name__ == '__main__:'
suite.
if __file__ == $0
).Add an END
at last before alias name.
CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
For example:
SELECT CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
FROM TableName
Got a gotcha for those with their headspace in Pandas and moving to pyspark
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext
spark_conf = SparkConf().setMaster("local").setAppName("MyAppName")
sc = SparkContext(conf = spark_conf)
sqlContext = SQLContext(sc)
records = [
{"colour": "red"},
{"colour": "blue"},
{"colour": None},
]
pandas_df = pd.DataFrame.from_dict(records)
pyspark_df = sqlContext.createDataFrame(records)
So if we wanted the rows that are not red:
pandas_df[~pandas_df["colour"].isin(["red"])]
Looking good, and in our pyspark DataFrame
pyspark_df.filter(~pyspark_df["colour"].isin(["red"])).collect()
So after some digging, I found this: https://issues.apache.org/jira/browse/SPARK-20617 So to include nothingness in our results:
pyspark_df.filter(~pyspark_df["colour"].isin(["red"]) | pyspark_df["colour"].isNull()).show()
Check out this link (Running react-native run-ios occurs an error?). It appears to be a problem with the location of Command line tools
.
In Xcode, select Xcode menu, then Preferences, then Locations tab. Select your Xcode version from the dropdown and exit Xcode.
The following function will work in JDK version 1.5 and above.
public String getSimpleName()
Refining Günter Zöchbauer answer:
This appears to be different now. I was trying to do this to conditionally apply an href attribute to an anchor tag. You must use undefined for the 'do not apply' case. As an example, I'll demonstrate with a link conditionally having an href attribute applied.
--EDIT--
It looks like angular has changed some things, so null
will now work as expected. I've update the example to use null
rather than undefined
.
An anchor tag without an href attribute becomes plain text, indicating a placeholder for a link, per the hyperlink spec.
For my navigation, I have a list of links, but one of those links represents the current page. I didn't want the current page link to be a link, but still want it to appear in the list (it has some custom styles, but this example is simplified).
<a [attr.href]="currentUrl !== link.url ? link.url : null">
This is cleaner than using two *ngIf's on a span and anchor tag, I think. It's also perfect for adding a disabled attribute to a button.
void
is a reserved JavaScript keyword. It evaluates the expression and always returns undefined
.
By default, you need to use keys to ssh into your google compute engine machine, but you can turn on password authentication if you do not need that level of security.
Tip: Use the Open in browser window SSH option from your cloud console to gain access to the machine. Then switch to the root user with
sudo su - root
to make the configuration changes below.
/etc/ssh/sshd_config
file.PasswordAuthentication
and ChallengeResponseAuthentication
to yes
./etc/init.d/ssh restart
.Have you tried simply 'reboot' with adb?
adb reboot
Also you can run complete shell scripts (e.g. to reboot your emulator) via adb:
adb shell <command>
The official docs can be found here.
Project > Generate Javadoc....
In the Javadoc command: field, browse to find javadoc.exe (usually at [path_to_jdk_directory]\bin\javadoc.exe).
Check the box next to the project/package/file for which you are creating the Javadoc.
In the Destination: field, browse to find the desired destination (for example, the root directory of the current project).
Click Finish.
You should now be able to find the newly generated Javadoc in the destination folder. Open index.html.
I like:
Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
myDate.ToString(timeFormat)
Easy to maintain if you need to use it in several parts of your code, date formats always seem to change sooner or later.
This is possible if you have an existing Newline character in the row or another row.
Select the square-box that represents the existing Newline character, copy it (control-C), and then paste it (control-V) where you want it to be.
This is slightly cheesy, but I actually did get it to work in SSMS 2008 and I was not able to get any of the other suggestions (control-enter, alt-13, or any alt-##) to work.
You can try like this:
private String getCharForNumber(int i) {
CharSequence css = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (i > 25) {
return null;
}
return css.charAt(i) + "";
}
CSS Keyframes support is pretty good these days:
.fade-in {_x000D_
opacity: 1;_x000D_
animation-name: fadeInOpacity;_x000D_
animation-iteration-count: 1;_x000D_
animation-timing-function: ease-in;_x000D_
animation-duration: 2s;_x000D_
}_x000D_
_x000D_
@keyframes fadeInOpacity {_x000D_
0% {_x000D_
opacity: 0;_x000D_
}_x000D_
100% {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<h1 class="fade-in">Fade Me Down Scotty</h1>
_x000D_
For me, it only happened on some pages because I used window.location
instead of $location.url(...);
This fixed my problem. Took a while to figure out :)
Thou shalt always encode URLs.
Here is how Ruby encodes your URL:
irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"
In Visual Studio 2015 Update3 I have this feature.
Just by highlighting properties and then press Ctrl + . and then press Generate Constructor.
For example, if you've highlighted two properties it will suggest you to create a constructor with two parameters and if you've selected three it will suggest one with three parameters and so on.
It also works with Visual Studio 2017 and 2019.
After digging a lot of stuff, finally, I came up with a good solution that doesn't hang the CI :) Suit it to your needs!
public static Task WaitUntil<T>(T elem, Func<T, bool> predicate, int seconds = 10)
{
var tcs = new TaskCompletionSource<int>();
using(var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(seconds)))
{
cancellationTokenSource.Token.Register(() =>
{
tcs.SetException(
new TimeoutException($"Waiting predicate {predicate} for {elem.GetType()} timed out!"));
tcs.TrySetCanceled();
});
while(!cancellationTokenSource.IsCancellationRequested)
{
try
{
if (!predicate(elem))
{
continue;
}
}
catch(Exception e)
{
tcs.TrySetException(e);
}
tcs.SetResult(0);
break;
}
return tcs.Task;
}
}
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
this could work for you.
using System.Linq;
DirectoryInfo info = new DirectoryInfo("PATH_TO_DIRECTORY_HERE");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
{
// DO Something...
}
Just another example using HTML and CSS:
<div style="width: Auto; margin: 0 auto;">Hello</div>
I had do this kind of automatic validation in VB and this is how I did it (converted to C#):
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = settings.ValidationFlags |
Schema.XmlSchemaValidationFlags.ProcessSchemaLocation;
XmlReader XMLvalidator = XmlReader.Create(reader, settings);
Then I subscribed to the settings.ValidationEventHandler
event while reading the file.
There are several ways to create a favicon. The best way for you depends on various factors:
If you want to get the job done well and quickly, you can use a favicon generator. This one creates the pictures and HTML code for all major desktop and mobiles browsers. Full disclosure: I'm the author of this site.
Advantages of such solution: it's quick and all compatibility considerations were already addressed for you.
As you suggest, you can create a favicon.ico
file which contains 16x16 and 32x32 pictures (note that Microsoft recommends 16x16, 32x32 and 48x48).
Then, declare it in your HTML code:
<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
This method will work with all desktop browsers, old and new. But most mobile browsers will ignore the favicon.
About your suggestion of placing the favicon.ico
file in the root and not declaring it: beware, although this technique works on most browsers, it is not 100% reliable. For example Windows Safari cannot find it (granted: this browser is somehow deprecated on Windows, but you get the point). This technique is useful when combined with PNG icons (for modern browsers).
In your question, you do not mention the mobile browsers. Most of them will ignore the favicon.ico
file. Although your site may be dedicated to desktop browsers, chances are that you don't want to ignore mobile browsers altogether.
You can achieve a good compatibility with:
favicon.ico
, see above.Declare them with
<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
<link rel="icon" type="image/png" href="/path/to/icons/favicon-192x192.png" sizes="192x192">
<link rel="apple-touch-icon" sizes="180x180" href="/path/to/icons/apple-touch-icon-180x180.png">
This is not the full story, but it's good enough in most cases.
script1.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170
This error happens due to a security measure which won't let scripts be executed on your system without you having approved of it. You can do so by opening up a powershell with administrative rights (search for powershell in the main menu and select Run as administrator from the context menu) and entering:
set-executionpolicy remotesigned
(I found this answer from a video: http://www.youtube.com/watch?v=xmvRF7koJ5E)
Download msvcp71.dll
and msvcr71.dll
from the web.
Save them to your C:\Windows\System32
folder.
Save them to your C:\Windows\SysWOW64
folder as well (if you have a 64-bit operating system).
Now try running your code file in Python and it will load the graph in couple of seconds.
shell> mysql_config_editor set --login-path=local
--host=localhost --user=localuser --password
Enter password: enter password "localpass" here
shell> mysql_config_editor set --login-path=remote
--host=remote.example.com --user=remoteuser --password
Enter password: enter password "remotepass" here
To see what mysql_config_editor wrote to the .mylogin.cnf file, use the print command:
shell> mysql_config_editor print --all
[local]
user = localuser
password = *****
host = localhost
[remote]
user = remoteuser
password = *****
host = remote.example.com
The print command displays each login path as a set of lines beginning with a group header indicating the login path name in square brackets, followed by the option values for the login path. Password values are masked and do not appear as clear text.
As shown by the preceding examples, the .mylogin.cnf file can contain multiple login paths. In this way, mysql_config_editor makes it easy to set up multiple “personalities” for connecting to different MySQL servers. Any of these can be selected by name later using the --login-path option when you invoke a client program. For example, to connect to the local server, use this command:
shell> mysql --login-path=local
To connect to the remote server, use this command:
shell> mysql --login-path=remote
If the tables are innodb you can create it like this:
CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id ),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
) ENGINE=INNODB;
You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look here for more info.
0.0 is a double literal and this is not considered as absolute zero! No exception because it is considered that the double variable large enough to hold the values representing near infinity!
It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.
Have you tried JQuery? Vanilla javascript can be tough. Try using this:
$('.container-element').add('<div>Insert Div Content</div>');
.container-element
is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add()
function inserts HTML into the container-element.
I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.
BE MINDFUL, If you use angular.equals()
on objects that have property obj.$something
(property name starts with $) those properties will get ignored in comparison.
Example:
var obj1 = {
$key0: "A",
key1: "value1",
key2: "value2",
key3: {a: "aa", b: "bb"}
}
var obj2 = {
$key0: "B"
key2: "value2",
key1: "value1",
key3: {a: "aa", b: "bb"}
}
angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)
Not including the action attribute opens the page up to iframe clickjacking attacks, which involve a few simple steps:
References
You could use:
parentWindow.maxsize(#,#);
parentWindow.minsize(x,x);
At the bottom of your code to set the fixed window size.
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).
At most one parameter is allowed to read from the message body. So this will not work:
// Caution: Will not work!
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.
Please go through the website for more details: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
Did anyone tried this pure Java solution (without SpringUtils):
//decimal to hex string 1=> 01, 10=>0A,..
String.format("%1$2s", Integer.toString(1,16) ).replace(" ","0");
//reply to original question, string with leading zeros.
//first generates a 10 char long string with leading spaces, and then spaces are
//replaced by a zero string.
String.format("%1$10s", "mystring" ).replace(" ","0");
Unfortunately this solution works only if you do not have blank spaces in a string.
if you are willing to use an external library, check out http://crsmithdev.com/arrow/
U can then get the last day of the month with:
import arrow
arrow.utcnow().ceil('month').date()
This returns a date object which you can then do your manipulation.
As others have noted, embedding function pointers directly inside your structure is usually reserved for special purposes, like a callback function.
What you probably want is something more like a virtual method table.
typedef struct client_ops_t client_ops_t;
typedef struct client_t client_t, *pno;
struct client_t {
/* ... */
client_ops_t *ops;
};
struct client_ops_t {
pno (*AddClient)(client_t *);
pno (*RemoveClient)(client_t *);
};
pno AddClient (client_t *client) { return client->ops->AddClient(client); }
pno RemoveClient (client_t *client) { return client->ops->RemoveClient(client); }
Now, adding more operations does not change the size of the client_t
structure. Now, this kind of flexibility is only useful if you need to define many kinds of clients, or want to allow users of your client_t
interface to be able to augment how the operations behave.
This kind of structure does appear in real code. The OpenSSL BIO layer looks similar to this, and also UNIX device driver interfaces have a layer like this.
To start the process with parameters, you can use following code:
string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);
To kill/exit the program again, you can use following code:
proc.CloseMainWindow();
proc.Close();
I'm calling powershell from cmd, and passing quotes and neither escapes here worked. The grave accent worked to escape double quotes on this Win 10 surface pro.
>powershell.exe "echo la`"" >> test
>type test
la"
Below are outputs I got for other characters to escape a double quote:
la\
la^
la
la~
Using another quote to escape a quote resulted in no quotes. As you can see, the characters themselves got typed, but didn't escape the double quotes.
I see a couple of issues.
First:
ser.read() is only going to return 1 byte at a time.
If you specify a count
ser.read(5)
it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)
If you know that your input is always properly terminated with EOL characters, better way is to use
ser.readline()
That will continue to read characters until an EOL is received.
Second:
Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.
Get rid of the
for line in ser.read():
and just say:
line = ser.readline()
You can also do
Pushd "%~dp0"
Which also takes running from a unc path into consideration.
you should use only english version of phpmyadmin if you are using all languages you should enable all languages mbstring in php.in file.....just search for mbstring in php.in
The problem is caused by the fact that the Model
's toArray()
method ignores any accessors which do not directly relate to a column in the underlying table.
As Taylor Otwell mentioned here, "This is intentional and for performance reasons." However there is an easy way to achieve this:
class EventSession extends Eloquent {
protected $table = 'sessions';
protected $appends = array('availability');
public function getAvailabilityAttribute()
{
return $this->calculateAvailability();
}
}
Any attributes listed in the $appends property will automatically be included in the array or JSON form of the model, provided that you've added the appropriate accessor.
Old answer (for Laravel versions < 4.08):
The best solution that I've found is to override the toArray()
method and either explicity set the attribute:
class Book extends Eloquent {
protected $table = 'books';
public function toArray()
{
$array = parent::toArray();
$array['upper'] = $this->upper;
return $array;
}
public function getUpperAttribute()
{
return strtoupper($this->title);
}
}
or, if you have lots of custom accessors, loop through them all and apply them:
class Book extends Eloquent {
protected $table = 'books';
public function toArray()
{
$array = parent::toArray();
foreach ($this->getMutatedAttributes() as $key)
{
if ( ! array_key_exists($key, $array)) {
$array[$key] = $this->{$key};
}
}
return $array;
}
public function getUpperAttribute()
{
return strtoupper($this->title);
}
}
Here's a better approach where you don't have to delete/move anything for Android Studio 3.+.
File > Close Project
.[^a-zA-Z\d\s:]
Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule
I think this is the simple form
Button1.layer.cornerRadius = 10(Half of the length and width)
Button1.layer.borderWidth = 2
I get the same error when I specify my HTTPS URL as : https://www.mywebsite.com . However it works fine when I specify it without the three W's as : https://mywebsite.com .
All of this works for me:
@Echo Off
Echo Directory = %~dp0
Echo Object Name With Quotations=%0
Echo Object Name Without Quotes=%~0
Echo Bat File Drive = %~d0
Echo Full File Name = %~n0%~x0
Echo File Name Without Extension = %~n0
Echo File Extension = %~x0
Pause>Nul
Output:
Directory = D:\Users\Thejordster135\Desktop\Code\BAT\
Object Name With Quotations="D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat"
Object Name Without Quotes=D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat
Bat File Drive = D:
Full File Name = Path.bat
File Name Without Extension = Path
File Extension = .bat
POST and GET are two HTTP request methods. GET is usually intended to retrieve some data, and is expected to be idempotent (repeating the query does not have any side-effects) and can only send limited amounts of parameter data to the server. GET requests are often cached by default by some browsers if you are not careful.
POST is intended for changing the server state. It carries more data, and repeating the query is allowed (and often expected) to have side-effects such as creating two messages instead of one.
For the folks who are using Java based Spring configuration:
@Configuration
@ComponentScan(basePackages = "com.domain.sample")
@EnableWebMvc
public class SpringConfig extends WebMvcConfigurerAdapter {
....
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
converter.setObjectMapper(objectMapper);
converters.add(converter);
super.configureMessageConverters(converters);
}
....
}
I'm using MappingJackson2HttpMessageConverter
- which is from fasterxml.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.1</version>
</dependency>
If you want to use codehaus-jackson mapper, instead use this one MappingJacksonHttpMessageConverter
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${codehaus.jackson.version}</version>
</dependency>
CURDATE()
will give current date while NOW()
will give full date time.
Run the queries, and you will find out whats the difference between them.
SELECT NOW(); -- You will get 2010-12-09 17:10:18
SELECT CURDATE(); -- You will get 2010-12-09
This is documented in section 3.9.3 of the Spring 3.0 manual:
For a fallback match, the bean name is considered a default qualifier value.
In other words, the default behaviour is as though you'd added @Qualifier("country")
to the setter method.
SELECT *
FROM (
SELECT TOP 20
t.*, ROW_NUMBER() OVER (ORDER BY field1) AS rn
FROM table1 t
ORDER BY
field1
) t
WHERE rn > 10
Using Qt in Python is a really pleasant experience: http://wiki.python.org/moin/PyQt
For the quick tutorial: http://zetcode.com/tutorials/pyqt4/
1) If you are limited to the double
precision, one reason to use BigDecimal
s is to realize operations with the BigDecimal
s created from the double
s.
2) The BigDecimal
consists of an arbitrary precision integer unscaled value and a non-negative 32-bit integer scale, while the double wraps a value of the primitive type double
in an object. An object of type Double
contains a single field whose type is double
3) It should make no difference
You should have no difficulties with the $ and precision. One way to do it is using System.out.printf
Seems like SQL Server 2012 can handle the old update syntax of Teradata too:
UPDATE a
SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a, table2 b
WHERE
b.[common field]= a.commonfield
AND a.BatchNO = '110'
If I remember correctly, 2008R2 was giving error when I tried similar query.
Note: If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground.
If an app needs to create a foreground service, the app should call startForegroundService()
. That method creates a background service, but the method signals to the system that the service will promote itself to the foreground.
Once the service has been created, the service must call its startForeground() method within five seconds.
I was looking similar but I wanted the difference in either list (uncommon elements between the 2 lists).
Let say I have:
List<String> oldKeys = Arrays.asList("key0","key1","key2","key5");
List<String> newKeys = Arrays.asList("key0","key2","key5", "key6");
And I wanted to know which key has been added and which key is removed i.e I wanted to get (key1, key6)
Using org.apache.commons.collections.CollectionUtils
List<String> list = new ArrayList<>(CollectionUtils.disjunction(newKeys, oldKeys));
Result
["key1", "key6"]
You can do this with a pivot table and add a line with the pourcentage for each category like brettdj showed in his answer. But if you want to keep your data as it is, there is a solution by using some javascript.
Javascript is a powerful language offering a lot of useful data visualization libraries like plotly.js.
Here is a working code I have written for you:
https://www.funfun.io/1/#/edit/5a58c6368dfd67466879ed27
In this example, I use a Json file to get the data from the embedded spreadsheet, so I can use it in my javascript code and create a bar chart.
I calculate the percentage by adding the values of all the category present in the table and using this formula (you can see it in the script.js file):
Percentage (%) = 100 x partial value / total value
It automatically calculates the total and pourcentage even if you add more categories.
I used plotly.js to create my chart, it has a good documentation and lots of examples for beginners, this code gets all the option you want to use:
var trace1 = {
x: xValue,
y: data,
type: 'bar',
text: yValue,
textposition: 'auto',
hoverinfo: 'none',
marker: {
color: 'yellow',
opacity: 0.6,
line: {
color: 'yellow',
width: 1.5
}
}
};
It is rather self explanatory, the text
is where you put the percentage.
Once you've made your chart you can load it in excel by passing the URL in the Funfun add-in. Here is how it looks like with my example:
I know it is an old post but I hope it helps people with the same problem !
Disclosure : I’m a developer of funfun
unicode('foo,bar').translate(dict([[ord(char), u''] for char in u',']))
Apparently, document.addEventListener()
is unreliable, and hence, my error. Use window.addEventListener()
with the same parameters, instead.
In my case i did following thing. In the UserMaster userId is PK and in UserAccess userId is FK of UserMaster
UserAccess.belongsTo(UserMaster,{foreignKey: 'userId'});
UserMaster.hasMany(UserAccess,{foreignKey : 'userId'});
var userData = await UserMaster.findAll({include: [UserAccess]});
If you are sure you haven't messed the jar, then please clean the project and perform mvn clean install
. This should solve the problem.
I have also seen this error on Xcode 7.2 when the derived data becomes corrupted (in my case I interrupted a build and suspect that was the root cause).
So if the other solutions (notably Chris's and BraveS's which I suspect are more likely) do not fit your problem try deleting derived data (Select: Window / Projects / Derived Data -> Delete) and re-building.
(Added for reference by others - I know the original question has been answered correctly).
If the variable is same, then
: "${VARIABLE:=DEFAULT_VALUE}"
assigns DEFAULT_VALUE
to VARIABLE
if not defined. The double quotes prevent globbing and word splitting.
Also see Section 3.5.3, Shell Parameter Expansion, in the Bash manual.
it works for me fine, if you a have string, then simply explode it first.
$emails = array();
Mail::send('emails.maintenance',$mail_params, function($message) use ($emails) {
foreach ($emails as $email) {
$message->to($email);
}
$message->subject('My Email');
});
I think the problem is with the datatype of the data you are passing Caused by: java.sql.SQLException: Invalid column type: 1111
check the datatypes you pass with the actual column datatypes may be there can be some mismatch or some constraint violation with null
If you have configured the "difftool" you can use
git difftool revision_1:file_1 revision_2:file_2
Example: Comparing a file from its last commit to its previous commit on the same branch: Assuming that if you are in your project root folder
$git difftool HEAD:src/main/java/com.xyz.test/MyApp.java HEAD^:src/main/java/com.xyz.test/MyApp.java
You should have the following entries in your ~/.gitconfig or in project/.git/config file. Install the p4merge [This is my preferred diff and merge tool]
[merge]
tool = p4merge
keepBackup = false
[diff]
tool = p4merge
keepBackup = false
[difftool "p4merge"]
path = C:/Program Files (x86)/Perforce/p4merge.exe
[mergetool]
keepBackup = false
[difftool]
keepBackup = false
[mergetool "p4merge"]
path = C:/Program Files (x86)/Perforce/p4merge.exe
cmd = p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\"
In Python2, input
is evaluated, input()
is equivalent to eval(raw_input())
. When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.
Use raw_input
to get a string from the user in Python2.
Demo 1: klj
is not defined:
>>> input()
klj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'klj' is not defined
Demo 2: klj
is defined:
>>> klj = 'hi'
>>> input()
klj
'hi'
Demo 3: getting a string with raw_input
:
>>> raw_input()
klj
'klj'