You can use the dotenv package no matter what setup you use. It allows you to create a .env in your project root and specify your keys like so
REACT_APP_SERVER_PORT=8000
In your applications entry file your just call dotenv(); before accessing the keys like so
process.env.REACT_APP_SERVER_PORT
I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!
This is my working example:
Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
' in duplicated formatting rules that in turn will significantly slow down
' the spreadsheet.
' This macro is designed to reset all formatting rules to default.
' ----------------------------------------------------------------------------------------
On Error GoTo ErrHandler
' Make sure we are positioned in the correct sheet
WS_PROMO.Select
' Disable Events
Application.EnableEvents = False
' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete
' CREATE ALL THE CONDITIONAL FORMATTING RULES:
' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
.Font.Color = -16776961
.StopIfTrue = False
End With
' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
.Font.Color = -16744448
.StopIfTrue = False
End With
' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
.Font.Bold = True
.Font.Color = -16776961
.StopIfTrue = False
End With
' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
.Font.Bold = True
.Font.Color = -10092544
.StopIfTrue = False
End With
' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
.DupeUnique = xlDuplicate
.Font.Color = -16383844
.Interior.Color = 13551615
.StopIfTrue = False
End With
' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
.Font.Bold = True
.Interior.Color = 13434879
.StopIfTrue = False
End With
' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")
ErrHandler:
Application.EnableEvents = False
End Sub
If you wanted to simply assign some variables for later use, you can do them in one shot with something along these lines:
declare @var1 int,@var2 int,@var3 int;
select
@var1 = field1,
@var2 = field2,
@var3 = field3
from
table
where
condition
If that's the type of thing you're after
You have to write a specific media query for this, from your question, below 768px, the navbar will collapse, so apply it above 768px and below 1000px, just like that:
@media (min-width: 768px) and (max-width: 1000px) {
.collapse {
display: none !important;
}
}
This will hide the navbar collapse until the default occurrence of the bootstrap unit. As the collapse class flips the inner assets inside navbar collapse will be automatically hidden, like wise you have to set your css as you desired design.
You can use Random.Next(int maxValue)
:
Return: A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.
var r = new Random();
// print random integer >= 0 and < 100
Console.WriteLine(r.Next(100));
For this case however you could use Random.Next(int minValue, int maxValue)
, like this:
// print random integer >= 1 and < 101
Console.WriteLine(r.Next(1, 101);)
// or perhaps (if you have this specific case)
Console.WriteLine(r.Next(100) + 1);
While probably not related to your problem, I had the same issue today. As it turns out, I had enabled an URL Rewrite module to force my site to use HTTPS instead of HTTP and on my production environment, this worked just fine. But on my development system, where it runs as an application within my default site, it failed...
As it turns out, my default site had no binding for HTTPS so the rewrite module would send me from HTTP to HTTPS, yet nothing was listening to the HTTPS port...
There's a chance that you have this issue for a similar reason. This error seems to occur if there's no proper binding for the site you're trying to access...
recently I saw that sometimes the flash player doesn't recognize &wmode=opaque
, istead you should pass &WMode=opaque
too (notice the uppercase).
The answer from Kukkuz did not work for me until I added in this dependency into the pom file:
<!-- Spring boot Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
From the guide here.
As well as updating the registry resources as outlined here.
It then started working just fine. If anyone in the future runs into the same issue and following the first answer does not solve your problem, follow these 2 other steps after utilizing the code in @Kukkuz's answer and see if that makes a difference.
add #include <iostream>
to the start of io.cpp
too.
I'm with Will:
I'll stick with that even if it means a lot of escaping.
I get the most value out of single quoted identifiers standing out because of the quotes. The rest of the practices are there just to give those single quoted identifiers some standing room.
def match_string(words):
nums = 0
letter = 0
other = 0
for i in words :
if i.isalpha():
letter+=1
elif i.isdigit():
nums+=1
else:
other+=1
return nums,letter,other
x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>
I'm new to R as well and faced the exact same problem. But then I looked at my data and noticed that it is being caused due to the fact that my csv file was using a comma separator (,) in all numeric columns (Ex: 1,233,444.56 instead of 1233444.56).
I removed the comma separator in my csv file and then reloaded into R. My data frame now recognises all columns as numbers.
I'm sure there's a way to handle this within the read.csv function itself.
Since Typescript 2.0, @types npm modules are used to import typings.
# Implementation package (required to run)
$ npm install --save lodash
# Typescript Description
$ npm install --save @types/lodash
Now since this question has been answered I'll go into how to efficiently import lodash
The failsafe way to import the entire library (in main.ts)
import 'lodash';
Implementing a lighter lodash with the functions you require
import chain from "lodash/chain";
import value from "lodash/value";
import map from "lodash/map";
import mixin from "lodash/mixin";
import _ from "lodash/wrapperLodash";
source: https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba#.kg6azugbd
PS: The above article is an interesting read on improving build time and reducing app size
If your detached HEAD is a fast forward of master and you just want the commits upstream, you can
git push origin HEAD:master
to push directly, or
git checkout master && git merge [ref of HEAD]
will merge it back into your local master.
Using WebClient.UploadString
or WebClient.UploadData
you can POST data to the server easily. I’ll show an example using UploadData, since UploadString is used in the same manner as DownloadString.
byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
System.Text.Encoding.ASCII.GetBytes("field1=value1&field2=value2") );
string sret = System.Text.Encoding.ASCII.GetString(bret);
Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -
sign before value
:
ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) +
geom_bar(stat = "identity")
which gives:
Used data:
corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
value = c(7L, 75L, 70L, 5L, 10L, 47L)),
class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))
Seems you are looking for ORDER BY
in DESC
ending order with LIMIT clause:
SELECT
*
FROM
scores
ORDER BY score DESC
LIMIT 10
Of course SELECT *
could seriously affect performance, so use it with caution.
Not sure why the first command is stopping. If you can make it parallel, you can try something like
start cmd.exe /C 1.bat
start cmd.exe /C 2.bat
Relying on the PDF that @CBroe posted earlier:
For best og:image results (retina ready & without being cropped) with the current Facebook Standard use:
Size: minimum 1200 x 630px
Ratio: 1.91:1
Add the following to your app build.gradle and select the specified release build variant and run
signingConfigs {
config {
keyAlias 'keyalias'
keyPassword 'keypwd'
storeFile file('<<KEYSTORE-PATH>>.keystore')
storePassword 'pwd'
}
}
buildTypes {
release {
debuggable true
signingConfig signingConfigs.config
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
For below Spring boot 2 version you need to use below code
server:
context-path: abc
And For Spring boot 2+ version use below code
server:
servlet:
context-path: abc
Look at the START command, you can do this:
START rest-of-your-program-name
For instance, this batch-file will wait until notepad exits:
@echo off
notepad c:\test.txt
However, this won't:
@echo off
start notepad c:\test.txt
Yes, but don't - escaping forward slashes is a good thing. When using JSON inside <script>
tags it's necessary as a </script>
anywhere - even inside a string - will end the script tag.
Depending on where the JSON is used it's not necessary, but it can be safely ignored.
Currently (Swift 2.1) you can check it using 3 ways:
Using '?' answered by @Sulthan
And using as?
operator:
if let delegateMe = self.delegate as? YourCustomViewController
{
delegateMe.onSuccess()
}
Basically it depends on what you are trying to achieve:
gcd = lambda m,n: m if not n else gcd(n,m%n)
The "BIGINT(20)" specification isn't a digit limit. It just means that when the data is displayed, if it uses less than 20 digits it will be left-padded with zeros. 2^64 is the hard limit for the BIGINT type, and has 20 digits itself, hence BIGINT(20) just means everything less than 10^20 will be left-padded with spaces on display.
is this what you want?
var grouped = CustomerList.GroupBy(m => m.GroupID).Select((n) => new { GroupId = n.Key, Items = n.ToList() });
I don't think there is a way to ignore adding DEFINER
s to the dump. But there are ways to remove them after the dump file is created.
Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost
with an empty string ""
Edit the dump (or pipe the output) using perl
:
perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
The accepted answer wasn't working for me when trying to parse the registry for uninstall strings, and execute them. Turns out I didn't need the call to Invoke-Expression
after all.
I finally came across this nice template for seeing how to execute uninstall strings:
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$app = 'MyApp'
$apps= @{}
Get-ChildItem $path |
Where-Object -FilterScript {$_.getvalue('DisplayName') -like $app} |
ForEach-Object -process {$apps.Set_Item(
$_.getvalue('UninstallString'),
$_.getvalue('DisplayName'))
}
foreach ($uninstall_string in $apps.GetEnumerator()) {
$uninstall_app, $uninstall_arg = $uninstall_string.name.split(' ')
& $uninstall_app $uninstall_arg
}
This works for me, namely because $app
is an in house application that I know will only have two arguments. For more complex uninstall strings you may want to use the join operator. Also, I just used a hash-map, but really, you'd probably want to use an array.
Also, if you do have multiple versions of the same application installed, this uninstaller will cycle through them all at once, which confuses MsiExec.exe
, so there's that too.
This re-installs all the dependencies and files of the package (like csc.exe)
Select Project->Properties from the menu bar.
Click C/C++ Build on the left in the dialog that comes up.
Based on this answer. It took some time for me to make this approach working, so I hope my answer will save someone's time.
Directive:
angular.module('app').directive('apsUploadFile', apsUploadFile);
function apsUploadFile() {
var directive = {
restrict: 'E',
templateUrl: 'upload.file.template.html',
link: apsUploadFileLink
};
return directive;
}
function apsUploadFileLink(scope, element, attrs) {
var input = $(element[0].querySelector('#fileInput'));
var button = $(element[0].querySelector('#uploadButton'));
var textInput = $(element[0].querySelector('#textInput'));
if (input.length && button.length && textInput.length) {
button.click(function (e) {
input.click();
});
textInput.click(function (e) {
input.click();
});
}
input.on('change', function (e) {
var files = e.target.files;
if (files[0]) {
scope.fileName = files[0].name;
} else {
scope.fileName = null;
}
scope.$apply();
});
}
upload.file.template.html
<input id="fileInput" type="file" class="ng-hide">
<md-button id="uploadButton"
class="md-raised md-primary"
aria-label="attach_file">
Choose file
</md-button>
<md-input-container md-no-float>
<input id="textInput" ng-model="fileName" type="text" placeholder="No file chosen" ng-readonly="true">
</md-input-container>
I've done something like this;
var certificationClass = _db.INDIVIDUALLICENSEs
.Join(_db.INDLICENSECLAsses,
IL => IL.LICENSE_CLASS,
ILC => ILC.NAME,
(IL, ILC) => new { INDIVIDUALLICENSE = IL, INDLICENSECLAsse = ILC })
.Where(o =>
o.INDIVIDUALLICENSE.GLOBALENTITYID == "ABC" &&
o.INDIVIDUALLICENSE.LICENSE_TYPE == "ABC")
.Select(t => new
{
value = t.PSP_INDLICENSECLAsse.ID,
name = t.PSP_INDIVIDUALLICENSE.LICENSE_CLASS,
})
.OrderBy(x => x.name);
Here is another alternate without reduce that performs well with large numbers. It uses sum
to flatten the list.
def factors(n):
return set(sum([[i, n//i] for i in xrange(1, int(n**0.5)+1) if not n%i], []))
If you are looping through a lot of cells, use the binary function, it is much faster. Using "<> 0" in place of "> 0" also makes it faster:
If InStrB(1, myString, "a", vbBinaryCompare) <> 0
If your data is already serialized:
a) send a JSON response
public function someAction()
{
$response = new Response();
$response->setContent(file_get_contents('path/to/file'));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
b) send a JSONP response (with callback)
public function someAction()
{
$response = new Response();
$response->setContent('/**/FUNCTION_CALLBACK_NAME(' . file_get_contents('path/to/file') . ');');
$response->headers->set('Content-Type', 'text/javascript');
return $response;
}
If your data needs be serialized:
c) send a JSON response
public function someAction()
{
$response = new JsonResponse();
$response->setData([some array]);
return $response;
}
d) send a JSONP response (with callback)
public function someAction()
{
$response = new JsonResponse();
$response->setData([some array]);
$response->setCallback('FUNCTION_CALLBACK_NAME');
return $response;
}
e) use groups in Symfony 3.x.x
Create groups inside your Entities
<?php
namespace Mindlahus;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* Some Super Class Name
*
* @ORM able("table_name")
* @ORM\Entity(repositoryClass="SomeSuperClassNameRepository")
* @UniqueEntity(
* fields={"foo", "boo"},
* ignoreNull=false
* )
*/
class SomeSuperClassName
{
/**
* @Groups({"group1", "group2"})
*/
public $foo;
/**
* @Groups({"group1"})
*/
public $date;
/**
* @Groups({"group3"})
*/
public function getBar() // is* methods are also supported
{
return $this->bar;
}
// ...
}
Normalize your Doctrine Object inside the logic of your application
<?php
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
// For annotations
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
...
$repository = $this->getDoctrine()->getRepository('Mindlahus:SomeSuperClassName');
$SomeSuperObject = $repository->findOneById($id);
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer($classMetadataFactory);
$callback = function ($dateTime) {
return $dateTime instanceof \DateTime
? $dateTime->format('m-d-Y')
: '';
};
$normalizer->setCallbacks(array('date' => $callback));
$serializer = new Serializer(array($normalizer), array($encoder));
$data = $serializer->normalize($SomeSuperObject, null, array('groups' => array('group1')));
$response = new Response();
$response->setContent($serializer->serialize($data, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;
$('</div>').attr('id', 'holdy').appendTo('body');
Here is code for numeric keyboard : keyboardType: TextInputType.phone When you add this code in textfield it will open numeric keyboard.
final _mobileFocus = new FocusNode();
final _mobile = TextEditingController();
TextFormField(
controller: _mobile,
focusNode: _mobileFocus,
maxLength: 10,
keyboardType: TextInputType.phone,
decoration: new InputDecoration(
counterText: "",
counterStyle: TextStyle(fontSize: 0),
hintText: "Mobile",
border: InputBorder.none,
hintStyle: TextStyle(
color: Colors.black,
fontSize: 15.0.
),
),
style: new TextStyle(
color: Colors.black,
fontSize: 15.0,
),
);
No you don't have to put credentials, You have to put headers on client side eg:
$http({
url: 'url of service',
method: "POST",
data: {test : name },
withCredentials: true,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
And and on server side you have to put headers to this is example for nodejs:
/**
* On all requests add headers
*/
app.all('*', function(req, res,next) {
/**
* Response settings
* @type {Object}
*/
var responseSettings = {
"AccessControlAllowOrigin": req.headers.origin,
"AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name",
"AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
"AccessControlAllowCredentials": true
};
/**
* Headers
*/
res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.
For more detail you can refer the link.
There is a RecyclerView subclass named HorizontalGridView you can use it to have horizontal direction. VerticalGridView for vertical direction
As a shorthand you can run:
docker tag d58 myname/server:latest
Where d58
represents the first 3 characters of the IMAGE ID,in this case, that's all you need.
Finally, you can remove the old image as follows:
docker rmi server
This worked for me!
App/build.gradle
//Add this....Keep both version same
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
First, it would be better if Java had tuples for returning multiple values.
Second, code the simplest possible Pair
class, or use an array.
But, if you do need to return a pair, consider what concept it represents (starting with its field names, then class name) - and whether it plays a larger role than you thought, and if it would help your overall design to have an explicit abstraction for it. Maybe it's a code hint
...
Please Note: I'm not dogmatically saying it will help, but just to look, to see if it does... or if it does not.
The map
method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!)
:
[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]
Array
and Range
are enumerable types. map
with a block returns an Array. map!
mutates the original array.
Where is this helpful, and what is the difference between map!
and each
? Here is an example:
names = ['danil', 'edmund']
# here we map one array to another, convert each element by some rule
names.map! {|name| name.capitalize } # now names contains ['Danil', 'Edmund']
names.each { |name| puts name + ' is a programmer' } # here we just do something with each element
The output:
Danil is a programmer
Edmund is a programmer
PHP regex strings need delimiters. Try:
$numpattern="/^([0-9]+)$/";
Also, note that you have a lower case o, not a zero. In addition, if you're just validating, you don't need the capturing group, and can simplify the regex to /^\d+$/
.
Example: http://ideone.com/Ec3zh
See also: PHP - Delimiters
&a
gives address of a
- &p
gives address of p
.
int * * p_to_p = &p;
How about the following?
<script charset='utf-8' type='text/javascript'>
jQuery(function($) { var a=$; a.noConflict();
//assumming that you are using an input text
// element with the text "nameGorge"
var itext_target = a("input[type='text']:contains('nameGorge')");
//gives the second part of the split which is 'Gorge'
itext_target.html().split("nameGorge")[1];
...
});
</script>
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
Java 8 alternative one-liner for merging two maps:
defaultMap.forEach((k, v) -> destMap.putIfAbsent(k, v));
The same with method reference:
defaultMap.forEach(destMap::putIfAbsent);
Or idemponent for original maps solution with third map:
Map<String, Integer> map3 = new HashMap<String, Integer>(map2);
map1.forEach(map3::putIfAbsent);
And here is a way to merge two maps into fast immutable one with Guava that does least possible intermediate copy operations:
ImmutableMap.Builder<String, Integer> builder = ImmutableMap.<String, Integer>builder();
builder.putAll(map1);
map2.forEach((k, v) -> {if (!map1.containsKey(k)) builder.put(k, v);});
ImmutableMap<String, Integer> map3 = builder.build();
See also Merge two maps with Java 8 for cases when values present in both maps need to be combined with mapping function.
String pooling
String pooling (sometimes also called as string canonicalisation) is a process of replacing several String objects with equal value but different identity with a single shared String object. You can achieve this goal by keeping your own Map (with possibly soft or weak references depending on your requirements) and using map values as canonicalised values. Or you can use String.intern() method which is provided to you by JDK.
At times of Java 6 using String.intern() was forbidden by many standards due to a high possibility to get an OutOfMemoryException if pooling went out of control. Oracle Java 7 implementation of string pooling was changed considerably. You can look for details in http://bugs.sun.com/view_bug.do?bug_id=6962931 and http://bugs.sun.com/view_bug.do?bug_id=6962930.
String.intern() in Java 6
In those good old days all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool. Besides explicitly interned strings, PermGen string pool also contained all literal strings earlier used in your program (the important word here is used – if a class or method was never loaded/called, any constants defined in it will not be loaded).
The biggest issue with such string pool in Java 6 was its location – the PermGen. PermGen has a fixed size and can not be expanded at runtime. You can set it using -XX:MaxPermSize=96m option. As far as I know, the default PermGen size varies between 32M and 96M depending on the platform. You can increase its size, but its size will still be fixed. Such limitation required very careful usage of String.intern – you’d better not intern any uncontrolled user input using this method. That’s why string pooling at times of Java 6 was mostly implemented in the manually managed maps.
String.intern() in Java 7
Oracle engineers made an extremely important change to the string pooling logic in Java 7 – the string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application. Technically, this alone could be a sufficient reason to reconsider using String.intern() in your Java 7 programs. But there are other reasons.
String pool values are garbage collected
Yes, all strings in the JVM string pool are eligible for garbage collection if there are no references to them from your program roots. It applies to all discussed versions of Java. It means that if your interned string went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.
Being eligible for garbage collection and residing in the heap, a JVM string pool seems to be a right place for all your strings, isn’t it? In theory it is true – non-used strings will be garbage collected from the pool, used strings will allow you to save memory in case then you get an equal string from the input. Seems to be a perfect memory saving strategy? Nearly so. You must know how the string pool is implemented before making any decisions.
adb kill-server
and adb start-server
only control the adb
daemon on the PC side. You need to restart adbd
daemon on the device itself after reverting the service.adb.root
property change done by adb root
:
~$ adb shell id
uid=2000(shell) gid=2000(shell)
~$ adb root
restarting adbd as root
~$ adb shell id
uid=0(root) gid=0(root)
~$ adb shell 'setprop service.adb.root 0; setprop ctl.restart adbd'
~$ adb shell id
uid=2000(shell) gid=2000(shell)
I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.
I checked play.google.com/store/apps/details?id=and.p2l&hl=en They are not locating the user's current location at all. So based on the number itself they are judging the location of the user. Like if the number starts from 240 ( in US) they they are saying location is Maryland but the person can be in California. So i don't think they are getting the user's location through LocationListner of Java at all.
Alternatively, you can use Commons Lang ArrayUtils class:
int[] arr = new int{3, 5, 1, 4, 2};
int indexOfTwo = ArrayUtils.indexOf(arr, 2);
There are overloaded variants of indexOf()
method for different array types.
It's not jquery (and it appears jquery has a workable solution) but just as another option....
I've had similar problems working heavily with SharePoint web services - you often need to pull data from multiple sources to generate input for a single process.
To solve it I embedded this kind of functionality into my AJAX abstraction library. You can easily define a request which will trigger a set of handlers when complete. However each request can be defined with multiple http calls. Here's the component (and detailed documentation):
This simple example creates one request with three calls and then passes that information, in the call order, to a single handler:
// The handler function
function AddUp(Nums) { alert(Nums[1] + Nums[2] + Nums[3]) };
// Create the pool
myPool = DP_AJAX.createPool();
// Create the request
myRequest = DP_AJAX.createRequest(AddUp);
// Add the calls to the request
myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [5,10]);
myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [4,6]);
myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [7,13]);
// Add the request to the pool
myPool.addRequest(myRequest);
Note that unlike many of the other solutions (including, I believe the "when" solution in jquery) provided this method does not force single threading of the calls being made - each will still run as quickly (or as slowly) as the environment allows but the single handler will only be called when all are complete. It also supports the setting of timeout values and retry attempts if your service is a little flakey.
I've found it insanely useful (and incredibly simple to understand from a code perspective). No more chaining, no more counting calls and saving output. Just "set it and forget it".
Never ever should you use money. It is not precise, and it is pure garbage; always use decimal/numeric.
Run this to see what I mean:
DECLARE
@mon1 MONEY,
@mon2 MONEY,
@mon3 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)
SELECT
@mon1 = 100, @mon2 = 339, @mon3 = 10000,
@num1 = 100, @num2 = 339, @num3 = 10000
SET @mon4 = @mon1/@mon2*@mon3
SET @num4 = @num1/@num2*@num3
SELECT @mon4 AS moneyresult,
@num4 AS numericresult
Output: 2949.0000 2949.8525
To some of the people who said that you don't divide money by money:
Here is one of my queries to calculate correlations, and changing that to money gives wrong results.
select t1.index_id,t2.index_id,(avg(t1.monret*t2.monret)
-(avg(t1.monret) * avg(t2.monret)))
/((sqrt(avg(square(t1.monret)) - square(avg(t1.monret))))
*(sqrt(avg(square(t2.monret)) - square(avg(t2.monret))))),
current_timestamp,@MaxDate
from Table1 t1 join Table1 t2 on t1.Date = traDate
group by t1.index_id,t2.index_id
Get the id of the div
whose content you want to change then assign the text as below:
var myDiv = document.getElementById("divId");
myDiv.innerHTML = "Content To Show";
For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:
function convertDate(date) {
// # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
var dateTimeParts = date.split(' ');
// # this assumes time format has NO SPACE between time and am/pm marks.
if (dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {
var theTime = dateTimeParts[1];
// # strip out all except numbers and colon
var ampm = theTime.replace(/[0-9:]/g, '');
// # strip out all except letters (for AM/PM)
var time = theTime.replace(/[[^a-zA-Z]/g, '');
if (ampm == 'pm') {
time = time.split(':');
// # if time is 12:00, don't add 12
if (time[0] == 12) {
time = parseInt(time[0]) + ':' + time[1] + ':00';
} else {
time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
}
} else { // if AM
time = time.split(':');
// # if AM is less than 10 o'clock, add leading zero
if (time[0] < 10) {
time = '0' + time[0] + ':' + time[1] + ':00';
} else {
time = time[0] + ':' + time[1] + ':00';
}
}
}
// # create a new date object from only the date part
var dateObj = new Date(dateTimeParts[0]);
// # add leading zero to date of the month if less than 10
var dayOfMonth = (dateObj.getDate() < 10 ? ("0" + dateObj.getDate()) : dateObj.getDate());
// # parse each date object part and put all parts together
var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;
// # finally combine re-formatted date and re-formatted time!
var date = new Date(yearMoDay + 'T' + time);
return date;
}
Usage:
date = convertDate('11/15/2016 2:00pm');
I just found my self with this Exception, I was trying to consume a JAX-WS, with a custom URL like this:
String WSDL_URL= <get value from properties file>;
Customer service = new Customer(new URL(WSDL_URL));
ExecutePtt port = service.getExecutePt();
return port.createMantainCustomers(part);
and Java threw:
XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,63]
Message: White spaces are required between publicId and systemId.
Turns out that the URL string used to construct the service was missing the "?wsdl" at the end. For instance:
Bad:
http://www.host.org/service/Customer
Good:
http://www.host.org/service/Customer?wsdl
Enter the following into the result cell and then press Ctrl & Shift while pushing ENTER:
=MIN(If(A1:E1>0,A1:E1))
You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);
, you just need to get rid of default sum(max_count)
. No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL
as the value for every cell in that column.
So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.
You also have the option to always COALESCE
the column to your desired default and leave it NULL
for now. This option fails when you want NULL
to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE
.
If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.
Rather than going for a direct command, please move required files to temp dir outside current dir. Then delete all files using rm *
or rm -r *
.
Then move required files to current dir.
You can't use float
inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle
.
So if you want to position child
element to right of parent
element you can use margin-left: auto
but now child
element will also push other div
to the right as you can see here Fiddle
.
What you can do now is change order of elements and set order: 2
on child
element so it doesn't affect second div
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
margin-left: auto;_x000D_
order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">Ignore parent?</div>_x000D_
<div>another child</div>_x000D_
</div>
_x000D_
I know this question is old, but was looking at this same issue, and one option would be to send date.valueOf() to the server instead. the valueOf() function of the javascript Date sends the number of milliseconds since midnight January 1, 1970 UTC.
In my case I convert DBresponse to XML in Camel ctx. JDBC executor return the ArrayList (rows) with LinkedCaseInsensitiveMap (single row). Task - create XML object based on DBResponce.
import java.io.StringWriter;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class ConvertDBToXMLProcessor implements Processor {
public void process(List body) {
if (body instanceof ArrayList) {
ArrayList<LinkedCaseInsensitiveMap> rows = (ArrayList) body;
DocumentBuilder builder = null;
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.newDocument();
Element rootElement = document.createElement("DBResultSet");
for (LinkedCaseInsensitiveMap row : rows) {
Element newNode = document.createElement("Row");
row.forEach((key, value) -> {
if (value != null) {
Element newKey = document.createElement((String) key);
newKey.setTextContent(value.toString());
newNode.appendChild(newKey);
}
});
rootElement.appendChild(newNode);
}
document.appendChild(rootElement);
/*
* If you need return string view instead org.w3c.dom.Document
*/
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
DOMSource domSource = new DOMSource(document);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.transform(domSource, result);
// return document
// return writer.toString()
}
}
}
One thing I've not seen anyone mention: the JSON file must have one line specifying the index the next line belongs to, for every line of the "pure" JSON file.
I.E.
{"index":{"_index":"shakespeare","_type":"act","_id":0}}
{"line_id":1,"play_name":"Henry IV","speech_number":"","line_number":"","speaker":"","text_entry":"ACT I"}
Without that, nothing works, and it won't tell you why
As part of Spring 4.1.1
onwards you now have full support of Java 8 Optional
(original ticket) therefore in your example both requests will go via your single mapping endpoint as long as you replace required=false
with Optional for your 3 params logout, name, password:
@RequestMapping (value = "/submit/id/{id}", method = RequestMethod.GET,
produces="text/xml")
public String showLoginWindow(@PathVariable("id") String id,
@RequestParam(value = "logout") Optional<String> logout,
@RequestParam("name") Optional<String> username,
@RequestParam("password") Optional<String> password,
@ModelAttribute("submitModel") SubmitModel model,
BindingResult errors) throws LoginException {...}
There are way too many ways to possibly discuss that you probably don't care about. You can hack of course - strace bash, or do all sorts of black magic running Bash in gdb.
You actually have two completely different examples there. <<<'string'
is already writing a string to a file. If anything is acceptable other than printf
, echo
, and cat
, you can use many other commands to behave like cat (sed, awk, tee, etc).
$ cp /dev/stdin ./tmpfooblah <<<'hello world'; cat tmpfooblah
hello world
Or hell, depending on how you've compiled Bash.
$ enable -f /usr/lib/bash/print print; print 'hello world' >tmpfile
If you want to use only bash strings and redirection, in pure bash, with no hacking, and no loadables, it is not possible. In ksh93 however, it is possible.
$ rm tmpfooblah; <<<'hello world' >tmpfooblah <##@(&!()); cat tmpfooblah
hello world
A much easier and shorted way which I am using to accomplish the same, using answer from another post, is like this:
var checkedCities = $('input[name=city]:checked').map(function() {
return this.value;
}).get();
Originally the cities are retrieved from a MySQL database, and looped in PHP while loop:
while ($data = mysql_fetch_assoc($all_cities)) {
<input class="city" name="city" id="<?php echo $data['city_name']; ?>" type="checkbox" value="<?php echo $data['city_id']; ?>" /><?php echo $data['city_name']; ?><br />
<?php } ?>
Now, using the above jQuery code, I get all the city_id values, and submit back to the database using $.get(...)
This has made my life so easy since now the code is fully dynamic. In order to add more cities, all I need to do is to add more cities in my database, and no worries on PHP or jQuery end.
You should be able to create and remove input field dynamically by using jquery using this method(https://www.adminspress.com/onex/view/uaomui), Even you can able to generate input fields in bulk and export to string.
The function below will return the x86 Program Files
directory in all of these three Windows configurations:
static string ProgramFilesx86()
{
if( 8 == IntPtr.Size
|| (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
var values = {};
$('td input').each(function(){
values[$(this).attr('name')] = $(this).val();
}
Haven't tested, but that should do it...
file()
is not supported in Python 3
Use open()
instead; see Built-in Functions - open().
You could put \s*
inbetween every character in your search string so if you were looking for cat you would use c\s*a\s*t\s*s\s*s
It's long but you could build the string dynamically of course.
You can see it working here: http://www.rubular.com/r/zzWwvppSpE
If they are unsorted, you can't do much but look at each one, which is O(N), and when you're done you'll know the minimum.
Pseudo-code:
small = <biggest value> // such as std::numerical_limits<int>::max
for each element in array:
if (element < small)
small = element
A better way reminded by Ben to me was to just initialize small with the first element:
small = element[0]
for each element in array, starting from 1 (not 0):
if (element < small)
small = element
The above is wrapped in the algorithm header as std::min_element.
If you can keep your array sorted as items are added, then finding it will be O(1), since you can keep the smallest at front.
That's as good as it gets with arrays.
I did it with this (change width, height, margin-top and margin-left accordingly):
.wrapper {
width:960px;
height:590px;
position:absolute;
top:50%;
left:50%;
margin-top:-295px;
margin-left:-480px;
}
<div class="wrapper"> -- Content -- </div>
Be sure you are setting PATH to Program Files (x86) not Program Files. That solved my problem.
calc(42px + (60 - 42) * (100vw - 768px) / (1440 - 768));
use this equation.
For anything larger or smaller than 1440 and 768, you can either give it a static value, or apply the same approach.
The drawback with vw solution is that you cannot set a scale ratio, say a 5vw at screen resolution 1440 may ended up being 60px font-size, your idea font size, but when you shrink the window width down to 768, it may ended up being 12px, not the minimal you want. With this approach, you can set your upper boundary and lower boundary, and the font will scale itself in between.
Remove the textnode, and replace the <b>
tag with whatever you need without ever touching the inputs :
$('#demoTable').find('tr > td').contents().filter(function() {
return this.nodeType===3;
}).remove().end().end()
.find('b').replaceWith($('<span />', {text: 'Hello Kitty'}));
Try this.Vals.replace(/("|')/g, "")
In JUnit 3, your field initializers will be run once per test method before any tests are run. As long as your field values are small in memory, take little set up time, and do not affect global state, using field initializers is technically fine. However, if those do not hold, you may end up consuming a lot of memory or time setting up your fields before the first test is run, and possibly even running out of memory. For this reason, many developers always set field values in the setUp() method, where it's always safe, even when it's not strictly necessary.
Note that in JUnit 4, test object initialization happens right before test running, and so using field initializers is safer, and recommended style.
>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print output
arg1 arg2
>>>
There is a bug in using of the subprocess.PIPE. For the huge output use this:
import subprocess
import tempfile
with tempfile.TemporaryFile() as tempf:
proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
proc.wait()
tempf.seek(0)
print tempf.read()
On your user model just add a 'hasRole' method like below
public boolean hasRole(String auth) {
for (Role role : roles) {
if (role.getName().equals(auth)) { return true; }
}
return false;
}
I usually use it to check if the authenticated user has the role admin as follows
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // This gets the authentication
User authUser = (User) authentication.getPrincipal(); // This gets the logged in user
authUser.hasRole("ROLE_ADMIN") // This returns true or false
Based on my own experiences and internet search, I find these places work:
/etc/paths.d
~/.bash_profile
Note that you should open a new terminal window to see the changes.
You may also refer to this this question
If you do not need more than strings, you can use com.google.common.io.Files
Files.simplifyPath("some/prefix/with//extra///slashes" + "file//name")
to get
"some/prefix/with/extra/slashes/file/name"
I was running zookeeper on Windows and wasn't able to stop ZooKeeper running at 2181 port using zookeeper-stop.sh, so tried this double slash "//" method to taskkill. It worked
1. netstat -ano | findstr :2181
TCP 0.0.0.0:2181 0.0.0.0:0 LISTENING 8876
TCP [::]:2181 [::]:0 LISTENING 8876
2.taskkill //PID 8876 //F
SUCCESS: The process with PID 8876 has been terminated.
There is also a DOM attribute called cdkFocusInitial
which works for me on inputs.
You can read more about it here: https://material.angular.io/cdk/a11y/overview
I just tried. If you execute the statement to generate your local table, the tool will accept that this column name exists. Just mark the table generation statement in your editor window and click execute.
I had the same problem using Apache commons-fileupload. I did not find out what causes the problems especially because I have the UTF-8 encoding in the following places: 1. HTML meta tag 2. Form accept-charset attribute 3. Tomcat filter on every request that sets the "UTF-8" encoding
-> My solution was to especially convert Strings from ISO-8859-1 (or whatever is the default encoding of your platform) to UTF-8:
new String (s.getBytes ("iso-8859-1"), "UTF-8");
hope that helps
Edit: starting with Java 7 you can also use the following:
new String (s.getBytes (StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
The following code works for me:
.half {
-moz-transform:scale(0.5);
-webkit-transform:scale(0.5);
transform:scale(0.5);
}
<img class="half" src="images/myimage.png">
I believe your 1:m relationships should already implicitly create DISTINCT JOINs.
But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.
SELECT DISTINCT a.valueA, c.valueC
FROM C
INNER JOIN B ON B.lookupC = C.id
INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC
Just wanted to add an option that I started using because I use Azure SQL and the multiple table thing was way too cumbersome for me. I added an insert/update/delete trigger on my table and then converted the before/after change to json using the "FOR JSON AUTO" feature.
SET @beforeJson = (SELECT * FROM DELETED FOR JSON AUTO)
SET @afterJson = (SELECT * FROM INSERTED FOR JSON AUTO)
That returns a JSON representation fo the record before/after the change. I then store those values in a history table with a timestamp of when the change occurred (I also store the ID for current record of concern). Using the serialization process, I can control how data is backfilled in the case of changes to schema.
I learned about this from this link here
Application Private Data files are stored within <internal_storage>/data/data/<package>
Files being stored in the internal storage can be accessed with openFileOutput() and openFileInput()
When those files are created as MODE_PRIVATE it is not possible to see/access them within another application such as a FileManager.
This command will "dry run" delete all remote (origin
) merged branches, apart from master
. You can change that, or, add additional branches after master: grep -v for-example-your-branch-here |
git branch -r --merged |
grep origin |
grep -v '>' |
grep -v master |
xargs -L1 |
awk '{sub(/origin\//,"");print}'|
xargs git push origin --delete --dry-run
If it looks good, remove the --dry-run
. Additionally, you may like to test this on a fork first.
The canonical use case in e-commerce is credit card expiration dates, MM/yy. Subtract one second instead of one day. Otherwise the card will appear expired for the entire last day of the expiration month.
DateTime expiration = DateTime.Parse("07/2013");
DateTime endOfTheMonthExpiration = new DateTime(
expiration.Year, expiration.Month, 1).AddMonths(1).AddSeconds(-1);
You can try FakeHttpContext:
using (new FakeHttpContext())
{
HttpContext.Current.Session["CustomerId"] = "customer1";
}
Try with this: http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOGL
It will return you all available details about the mentioned stock.
e.g. out put would look like below:
// [ {
"id": "694653"
,"t" : "GOOGL"
,"e" : "NASDAQ"
,"l" : "528.08"
,"l_fix" : "528.08"
,"l_cur" : "528.08"
,"s": "0"
,"ltt":"4:00PM EST"
,"lt" : "Dec 5, 4:00PM EST"
,"lt_dts" : "2014-12-05T16:00:14Z"
,"c" : "-14.50"
,"c_fix" : "-14.50"
,"cp" : "-2.67"
,"cp_fix" : "-2.67"
,"ccol" : "chr"
,"pcls_fix" : "542.58"
}
]
You can have your company stock symbol at the end of this URL to get its details:
http://finance.google.com/finance/info?client=ig&q=<YOUR COMPANY STOCK SYMBOL>
Changing XAMPP Default Port: If you want to get XAMPP up and running, you should consider changing the port from the default 80 to say 7777.
In the XAMPP Control Panel, click on the Apache – Config button which is located next to the ‘Logs’ button.
Select ‘Apache (httpd.conf)’ from the drop down. (Notepad should open)
Do Ctrl+F to find ’80’ and change line Listen 80 to Listen 7777
Find again and change line ServerName localhost:80 to ServerName localhost:7777
Save and re-start Apache. It should be running by now.
The only demerit to this technique is, you have to explicitly include the port number in the localhost url. Rather than http://localhost
it becomes http://localhost:7777
.
If you absolutely must use HTML to give your text color, you have to use the (deprecated) <font>
-tag:
<h2><font color="#006699">Process Report</font></h2>
But otherwise, I strongly recommend you to do as rekire said: use CSS.
It is now officially supported by Facebook. Just select the 'Button' layout.
In my case, all other solutions didn't work, but this one did:
obj = {...arr}
my arr is in a form: [name: "the name", email: "[email protected]"]
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
Try this:
void drawInitialNim(int num1, int num2, int num3){
int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function.
int i, j, k;
for(i=0; i<num1; i++)
board[0][i] = 'O';
for(i=0; i<num2; i++)
board[1][i] = 'O';
for(i=0; i<num3; i++)
board[2][i] = 'O';
for (j=0; j<3;j++) {
for (k=0; k<50; k++) {
if(board[j][k] != 0)
printf("%c", board[j][k]);
}
printf("\n");
}
}
Just Go To *Startmenu >>Java >>Configure Java >> Security >> Edit site list >> copy and paste your Link with problem >> OK Problem fixed :)*
The Following command displays extra informations
curl -X POST http://httpbin.org/post -v > /dev/null
You can ask server to send just HEAD, instead of full response
curl -X HEAD -I http://httpbin.org/
Note:
In some cases, server may send different headers for POST and HEAD. But in almost all cases headers are same.
You have to open chrome using the following flag Go to run menu and type "chrome --disable-web-security --user-data-dir"
Make sure all the instances of chrome are closed before you use the flag to open chrome. You will get a security warning that indicates CORS is enabled.
If you get that error message (Peer authentication failed for user (PG::Error)
) when running unit tests, make sure the test database exists.
The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie
results in another call to poruszanie
, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.
Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.
If XStream is a dependency, try:
new com.thoughtworks.xstream.converters.basic.DateConverter().toString(date)
Executive summary: it's 64 bits, or larger.
unsigned long long
is the same as unsigned long long int
. Its size is platform-dependent, but guaranteed by the C standard (ISO C99) to be at least 64 bits. There was no long long
in C89, but apparently even MSVC supports it, so it's quite portable.
In the current C++ standard (issued in 2003), there is no long long
, though many compilers support it as an extension. The upcoming C++0x standard will support it and its size will be the same as in C, so at least 64 bits.
You can get the exact size, in bytes (8 bits on typical platforms) with the expression sizeof(unsigned long long)
. If you want exactly 64 bits, use uint64_t
, which is defined in the header <stdint.h>
along with a bunch of related types (available in C99, C++11 and some current C++ compilers).
This is my Df contain 4 is repeated twice so here will remove repeated values.
scala> df.show
+-----+
|value|
+-----+
| 1|
| 4|
| 3|
| 5|
| 4|
| 18|
+-----+
scala> val newdf=df.dropDuplicates
scala> newdf.show
+-----+
|value|
+-----+
| 1|
| 3|
| 5|
| 4|
| 18|
+-----+
Faster way is below. Considering letters are only a-z,A-Z.
public static void main( String[] args ){
System.out.println(bestWay("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(isAlpha("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(bestWay("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(isAlpha("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
}
public static boolean bettertWay(String name) {
char[] chars = name.toCharArray();
long startTimeOne = System.nanoTime();
for(char c : chars){
if(!(c>=65 && c<=90)&&!(c>=97 && c<=122) ){
System.out.println(System.nanoTime() - startTimeOne);
return false;
}
}
System.out.println(System.nanoTime() - startTimeOne);
return true;
}
public static boolean isAlpha(String name) {
char[] chars = name.toCharArray();
long startTimeOne = System.nanoTime();
for (char c : chars) {
if(!Character.isLetter(c)) {
System.out.println(System.nanoTime() - startTimeOne);
return false;
}
}
System.out.println(System.nanoTime() - startTimeOne);
return true;
}
Runtime is calculated in nano seconds. It may vary system to system.
5748//bettertWay without numbers
true
89493 //isAlpha without numbers
true
3284 //bettertWay with numbers
false
22989 //isAlpha with numbers
false
Here's one generalized from something I just used. I'm posting it since it's a very simple example, and it demonstrates a practical use case along with default arguments:
#include <vector>
template <class T> class Alloc final { /*...*/ };
template <template <class T> class allocator=Alloc> class MyClass final {
public:
std::vector<short,allocator<short>> field0;
std::vector<float,allocator<float>> field1;
};
mysqldump -u root -p --all-databases > alldb.sql
Look up the documentation for mysqldump. You may want to use some of the options mentioned in comments:
mysqldump -u root -p --opt --all-databases > alldb.sql
mysqldump -u root -p --all-databases --skip-lock-tables > alldb.sql
mysql -u root -p < alldb.sql
I had a similar issue and found this thread. Replace didn't work for me, and going by the parent was difficult for my situation. Inner Html replaced the children, which wasn't what I wanted either. Using outerHTML got the job done. Hope this helps someone else!
currEl = <div>hello</div>
newElem = <span>Goodbye</span>
currEl.outerHTML = newElem
# currEl = <span>Goodbye</span>
To answer your question:
.html()
will just call .innerHTML
after doing some checks for nodeTypes and stuff. It also uses a try/catch
block where it tries to use innerHTML
first and if that fails, it'll fallback gracefully to jQuery's .empty()
+ append()
Had the same problem (is not a method) with jQuery when working on autocomplete. It appeared the code was executed before the autocomplete.js was loaded. So make sure the ui.colorpicker.js is loaded before calling colorpicker.
Here is a solution that leverages the use of Path.GetFullPath as recommended in the answer by @SLaks.
In the code that I am including here, note that IsValidPath(string path)
is designed such that the caller does not have to worry about exception handling.
You may also find that the method that it calls, TryGetFullPath(...)
, also has merit on its own when you wish to safely attempt to get an absolute path.
/// <summary>
/// Gets a value that indicates whether <paramref name="path"/>
/// is a valid path.
/// </summary>
/// <returns>Returns <c>true</c> if <paramref name="path"/> is a
/// valid path; <c>false</c> otherwise. Also returns <c>false</c> if
/// the caller does not have the required permissions to access
/// <paramref name="path"/>.
/// </returns>
/// <seealso cref="Path.GetFullPath"/>
/// <seealso cref="TryGetFullPath"/>
public static bool IsValidPath(string path)
{
string result;
return TryGetFullPath(path, out result);
}
/// <summary>
/// Returns the absolute path for the specified path string. A return
/// value indicates whether the conversion succeeded.
/// </summary>
/// <param name="path">The file or directory for which to obtain absolute
/// path information.
/// </param>
/// <param name="result">When this method returns, contains the absolute
/// path representation of <paramref name="path"/>, if the conversion
/// succeeded, or <see cref="String.Empty"/> if the conversion failed.
/// The conversion fails if <paramref name="path"/> is null or
/// <see cref="String.Empty"/>, or is not of the correct format. This
/// parameter is passed uninitialized; any value originally supplied
/// in <paramref name="result"/> will be overwritten.
/// </param>
/// <returns><c>true</c> if <paramref name="path"/> was converted
/// to an absolute path successfully; otherwise, false.
/// </returns>
/// <seealso cref="Path.GetFullPath"/>
/// <seealso cref="IsValidPath"/>
public static bool TryGetFullPath(string path, out string result)
{
result = String.Empty;
if (String.IsNullOrWhiteSpace(path)) { return false; }
bool status = false;
try
{
result = Path.GetFullPath(path);
status = true;
}
catch (ArgumentException) { }
catch (SecurityException) { }
catch (NotSupportedException) { }
catch (PathTooLongException) { }
return status;
}
public List<Requirement> listInquiryLogged()
{
using (DataClassesDataContext dt = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
{
var inq = new int[] {1683,1684,1685,1686,1687,1688,1688,1689,1690,1691,1692,1693};
var result = from Q in dt.Requirements
where inq.Contains(Q.ID)
orderby Q.Description
select Q;
return result.ToList<Requirement>();
}
}
I know this is an old question but I believe that my answer is one that might be helpful to some people who are looking for an easy, simple to understand pythonic way to detect OS in their code. Tested on python3.7
from sys import platform
class UnsupportedPlatform(Exception):
pass
if "linux" in platform:
print("linux")
elif "darwin" in platform:
print("mac")
elif "win" in platform:
print("windows")
else:
raise UnsupportedPlatform
You are logging sup
directly which is a string
console.log('sup')
Also you are using the wrong id
The template says #main_search
but you are using #searchBar
I suppose you are trying this out
$(function() {
var sup = $('#main_search').val('hi')
console.log(sup); // sup is a variable here
});
I found new library on GitHub: CharsetDetector/UTF-unknown
Charset detector build in C# - .NET Core 2-3, .NET standard 1-2 & .NET 4+
it's also a port of the Mozilla Universal Charset Detector based on other repositories.
CharsetDetector/UTF-unknown have a class named CharsetDetector
.
CharsetDetector
contains some static encoding detect methods:
CharsetDetector.DetectFromFile()
CharsetDetector.DetectFromStream()
CharsetDetector.DetectFromBytes()
detected result is in class DetectionResult
has attribute Detected
which is instance of class DetectionDetail
with below attributes:
EncodingName
Encoding
Confidence
below is an example to show usage:
// Program.cs
using System;
using System.Text;
using UtfUnknown;
namespace ConsoleExample
{
public class Program
{
public static void Main(string[] args)
{
string filename = @"E:\new-file.txt";
DetectDemo(filename);
}
/// <summary>
/// Command line example: detect the encoding of the given file.
/// </summary>
/// <param name="filename">a filename</param>
public static void DetectDemo(string filename)
{
// Detect from File
DetectionResult result = CharsetDetector.DetectFromFile(filename);
// Get the best Detection
DetectionDetail resultDetected = result.Detected;
// detected result may be null.
if (resultDetected != null)
{
// Get the alias of the found encoding
string encodingName = resultDetected.EncodingName;
// Get the System.Text.Encoding of the found encoding (can be null if not available)
Encoding encoding = resultDetected.Encoding;
// Get the confidence of the found encoding (between 0 and 1)
float confidence = resultDetected.Confidence;
if (encoding != null)
{
Console.WriteLine($"Detection completed: {filename}");
Console.WriteLine($"EncodingWebName: {encoding.WebName}{Environment.NewLine}Confidence: {confidence}");
}
else
{
Console.WriteLine($"Detection completed: {filename}");
Console.WriteLine($"(Encoding is null){Environment.NewLine}EncodingName: {encodingName}{Environment.NewLine}Confidence: {confidence}");
}
}
else
{
Console.WriteLine($"Detection failed: {filename}");
}
}
}
}
Use the fnReloadAjax() by the DataTables.net author.
I'm copying the source code below - in case the original ever moves:
$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
{
if ( typeof sNewSource != 'undefined' && sNewSource != null )
{
oSettings.sAjaxSource = sNewSource;
}
this.oApi._fnProcessingDisplay( oSettings, true );
var that = this;
var iStart = oSettings._iDisplayStart;
var aData = [];
this.oApi._fnServerParams( oSettings, aData );
oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
/* Clear the old information from the table */
that.oApi._fnClearTable( oSettings );
/* Got the data - add it to the table */
var aData = (oSettings.sAjaxDataProp !== "") ?
that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
for ( var i=0 ; i<aData.length ; i++ )
{
that.oApi._fnAddData( oSettings, aData[i] );
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
that.fnDraw();
if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
{
oSettings._iDisplayStart = iStart;
that.fnDraw( false );
}
that.oApi._fnProcessingDisplay( oSettings, false );
/* Callback user function - for event handlers etc */
if ( typeof fnCallback == 'function' && fnCallback != null )
{
fnCallback( oSettings );
}
}, oSettings );
}
/* Example call to load a new file */
oTable.fnReloadAjax( 'media/examples_support/json_source2.txt' );
/* Example call to reload from original file */
oTable.fnReloadAjax();
Instead of ng-options="product as product.label for product in products">
in the select element, you can even use this:
<option ng-repeat="product in products" value="{{product.label}}">{{product.label}}
which works just fine as well.
Newest version has better support literally for any generated Makefiles, through the compiledb
Three steps:
install compiledb
pip install compiledb
run a dry make
compiledb -n make
(do the autogen, configure if needed)
there will be a compile_commands.json file generated open the project and you will see CLion will load info from the json file. If you your CLion still try to find CMakeLists.txt and cannot read compile_commands.json, try to remove the entire folder, re-download the source files, and redo step 1,2,3
Orignal post: Working with Makefiles in CLion using Compilation DB
You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.
In 1985, individuals from companies throughout the computer industry joined together to develop the POSIX (Portable Operating System Interface for Computer Environments) standard, which is based largely on the UNIX System V Interface Definition (SVID) and other earlier standardization efforts. These efforts were spurred by the U.S. government, which needed a standard computing environment to minimize its training and procurement costs. Released in 1988, POSIX is a group of IEEE standards that define the API, shell, and utility interfaces for an operating system. Although aimed at UNIX-like systems, the standards can apply to any compatible operating system. Now that these stan- dards have gained acceptance, software developers are able to develop applications that run on all conforming versions of UNIX, Linux, and other operating systems.
From the book: A Practical Guide To Linux
Pymongo provides json_util - you can use that one instead to handle BSON types
def parse_json(data):
return json.loads(json_util.dumps(data))
Here are few tips on how to iterate a Set along with their performances:
public class IterateSet {
public static void main(String[] args) {
//example Set
Set<String> set = new HashSet<>();
set.add("Jack");
set.add("John");
set.add("Joe");
set.add("Josh");
long startTime = System.nanoTime();
long endTime = System.nanoTime();
//using iterator
System.out.println("Using Iterator");
startTime = System.nanoTime();
Iterator<String> setIterator = set.iterator();
while(setIterator.hasNext()){
System.out.println(setIterator.next());
}
endTime = System.nanoTime();
long durationIterator = (endTime - startTime);
//using lambda
System.out.println("Using Lambda");
startTime = System.nanoTime();
set.forEach((s) -> System.out.println(s));
endTime = System.nanoTime();
long durationLambda = (endTime - startTime);
//using Stream API
System.out.println("Using Stream API");
startTime = System.nanoTime();
set.stream().forEach((s) -> System.out.println(s));
endTime = System.nanoTime();
long durationStreamAPI = (endTime - startTime);
//using Split Iterator (not recommended)
System.out.println("Using Split Iterator");
startTime = System.nanoTime();
Spliterator<String> splitIterator = set.spliterator();
splitIterator.forEachRemaining((s) -> System.out.println(s));
endTime = System.nanoTime();
long durationSplitIterator = (endTime - startTime);
//time calculations
System.out.println("Iterator Duration:" + durationIterator);
System.out.println("Lamda Duration:" + durationLambda);
System.out.println("Stream API:" + durationStreamAPI);
System.out.println("Split Iterator:"+ durationSplitIterator);
}
}
The code is self explanatory.
The result of the durations are:
Iterator Duration: 495287
Lambda Duration: 50207470
Stream Api: 2427392
Split Iterator: 567294
We can see the Lambda
takes the longest while Iterator
is the fastest.
Frankly the errors are really hard to see, especially if only one character is "underwaved" in a sea of Java code. I used the instructions above to make the background an orangey-red color and things are much more obvious.
You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:
textBox1.Text = s ?? "Is null";
The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.
More info here: https://msdn.microsoft.com/en-us/library/ms173224.aspx
And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015
textBox1.Text = customer?.orders?[0].description ?? "n/a";
This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.
More info here: https://msdn.microsoft.com/en-us/library/dn986595.aspx
I figured out an elegant, Rails-like way to do it. First, rename your .scss
file to .scss.erb
, then use syntax like this (example for highlight_js-rails4 gem CSS asset):
@import "<%= asset_path("highlight_js/github") %>";
Why you can't host the file directly via SCSS:
Doing an @import
in SCSS works fine for CSS files as long as you explicitly use the full path one way or another. In development mode, rails s
serves assets without compiling them, so a path like this works...
@import "highlight_js/github.css";
...because the hosted path is literally /assets/highlight_js/github.css
. If you right-click on the page and "view source", then click on the link for the stylesheet with the above @import
, you'll see a line in there that looks like:
@import url(highlight_js/github.css);
The SCSS engine translates "highlight_js/github.css"
to url(highlight_js/github.css)
. This will work swimmingly until you decide to try running it in production where assets are precompiled have a hash injected into the file name. The SCSS file will still resolve to a static /assets/highlight_js/github.css
that was not precompiled and doesn't exist in production.
How this solution works:
Firstly, by moving the .scss
file to .scss.erb
, we have effectively turned the SCSS into a template for Rails. Now, whenever we use <%= ... %>
template tags, the Rails template processor will replace these snippets with the output of the code (just like any other template).
Stating asset_path("highlight_js/github")
in the .scss.erb
file does two things:
rake assets:precompile
task to precompile the appropriate CSS file.This also means that the SCSS engine isn't even parsing the CSS file; it's just hosting a link to it! So there's no hokey monkey patches or gross workarounds. We're serving a CSS asset via SCSS as intended, and using a URL to said CSS asset as Rails intended. Sweet!
I always think UNIX tools should be written as filters, read input from stdin and write output to stdout. If possible you could change your helloworld binary to write the contents of the text file to stdout rather than a specific file. That way you can use the shell to write your file anywhere.
$ cd ~/b
$ ~/a/helloworld > ~/c/helloworld.txt
If you mean by newline the newline character it is \n and \r is the carrier return character, but if you mean by newline the line ending then it depends on the operating system: DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n")
minimumFontSize
is deprecated in iOS 6.
So use minimumScaleFactor
instead of minmimumFontSize
.
lbl.adjustsFontSizeToFitWidth = YES
lbl.minimumScaleFactor = 0.5
Swift 5
lbl.adjustsFontSizeToFitWidth = true
lbl.minimumScaleFactor = 0.5
"Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section."
No one actually answered the above part of the original poster's question.
Here's the answer: http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/
As long as the value of width is auto, the element can have horizontal margin, padding and border without becoming wider than its container...
On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border... This may be what you want, but most likely it isn’t.
To visualise the difference I made an example: http://www.456bereastreet.com/lab/width-auto/
You can disable the event by applying following code:
with .attr()
API
$('#your_id').attr("disabled", "disabled");
or with .prop()
API
$('#your_id').prop('disabled', true);
It worked for me, but the exe4j can leave a signature when you double click the .exe application
This should work:
window.onload = function() {
document.getElementById('about').className = 'expand';
};
Or if you're using jQuery:
$(function() {
$('#about').addClass('expand');
});
Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
' replace the target with nothing
' Replace() returns a new String and does not modify the current one
Return stringToCleanUp.Replace(characterToRemove, "")
End Function
Here's more information about VB's Replace function
mysqldump --extended-insert=FALSE
Be aware that multiple inserts will be slower than one big insert.
Just call moment as a function without any arguments:
moment()
For timezone information with moment, look at the moment-timezone
package: http://momentjs.com/timezone/
I had to add the follow lines to my windows path to fix this. CMAKE should set the correct paths on install otherwise as long as you check the box. This is likely to be a different solution depending on the myriad of versions that are possible to install.
C:\msys64\mingw32\bin
C:\msys64\mingw64\bin
To open the terminal:
Please find more about integrated terminal here https://code.visualstudio.com/docs/editor/integrated-terminal
In order to get the http status code returned from the server, you can add validateStatus: status => true
to axios options:
axios({
method: 'POST',
url: 'http://localhost:3001/users/login',
data: { username, password },
validateStatus: () => true
}).then(res => {
console.log(res.status);
});
This way, every http response resolves the promise returned from axios.
If the list is sorted (as happens to be in the example) a binary search on index certainly works.
public static Dog Find(List<Dog> AllDogs, string Id)
{
int p = 0;
int n = AllDogs.Count;
while (true)
{
int m = (n + p) / 2;
Dog d = AllDogs[m];
int r = string.Compare(Id, d.Id);
if (r == 0)
return d;
if (m == p)
return null;
if (r < 0)
n = m;
if (r > 0)
p = m;
}
}
Not sure what the LINQ version of this would be.
To sandwich an my element between the modal screen and a dialog, I need to lift my element above the modal-screen, and then lift the dialog above my element.
I had a small success by doing the following after creating the dialog on element $dlg
.
$dlg.closest('.ui-dialog').css('zIndex',adjustment);
Since each dialog has a different starting z-index
(they incrementally get larger) I make adjustment
a string with a boost value, like this:
const adjustment = "+=99";
However, jQuery just keeps increasing the zIndex
value on the modal screen, so by the second dialog, the sandwich no longer worked. I gave up on ui-dialog "modal", made it "false", and just created my own modal. It imitates jQueryUI exactly. Here it is:
CoverAll = {};
CoverAll.modalDiv = null;
CoverAll.modalCloak = function(zIndex) {
var div = CoverAll.modalDiv;
if(!CoverAll.modalDiv) {
div = CoverAll.modalDiv = document.createElement('div');
div.style.background = '#aaaaaa';
div.style.opacity = '0.3';
div.style.position = 'fixed';
div.style.top = '0';
div.style.left = '0';
div.style.width = '100%';
div.style.height = '100%';
}
if(!div.parentElement) {
document.body.appendChild(div);
}
if(zIndex == null)
zIndex = 100;
div.style.zIndex = zIndex;
return div;
}
CoverAll.modalUncloak = function() {
var div = CoverAll.modalDiv;
if(div && div.parentElement) {
document.body.removeChild(div);
}
return div;
}
I had a similar problem - authenticate device and user at device. I used a Cookie
header alongside an Authorization: Bearer...
header. One header authenticated the device, the other authenticated the user. I used a Cookie
header because these are commonly used for authentication.
Meaning of a Const Member Function in C++ Common Knowledge: Essential Intermediate Programming gives a clear explanation:
The type of the this pointer in a non-const member function of a class X is X * const. That is, it’s a constant pointer to a non-constant X (see Const Pointers and Pointers to Const [7, 21]). Because the object to which this refers is not const, it can be modified. The type of this in a const member function of a class X is const X * const. That is, it’s a constant pointer to a constant X. Because the object to which this refers is const, it cannot be modified. That’s the difference between const and non-const member functions.
So in your code:
class foobar
{
public:
operator int () const;
const char* foo() const;
};
You can think it as this:
class foobar
{
public:
operator int (const foobar * const this) const;
const char* foo(const foobar * const this) const;
};
I've done a lot of this, and yes it sucks.
Some tips:
throwable
field and check it in tearDown
(see Listing 1). If you catch a bad exception in another thread, just assign it to throwable.AtomicBoolean
in your tests. It is thread safe, and you'll often need a final reference type to store values from callback classes and suchlike. See example in Listing 3.@Test(timeout=60*1000)
), as concurrency tests can sometimes hang forever when they're broken.Listing 1:
@After
public void tearDown() {
if ( throwable != null )
throw throwable;
}
Listing 2:
import static org.junit.Assert.fail;
import java.io.File;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Random;
import org.apache.commons.collections.Closure;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.time.StopWatch;
import org.easymock.EasyMock;
import org.easymock.classextension.internal.ClassExtensionHelper;
import static org.easymock.classextension.EasyMock.*;
import ca.digitalrapids.io.DRFileUtils;
/**
* Various utilities for testing
*/
public abstract class DRTestUtils
{
static private Random random = new Random();
/** Calls {@link #waitForCondition(Integer, Integer, Predicate, String)} with
* default max wait and check period values.
*/
static public void waitForCondition(Predicate predicate, String errorMessage)
throws Throwable
{
waitForCondition(null, null, predicate, errorMessage);
}
/** Blocks until a condition is true, throwing an {@link AssertionError} if
* it does not become true during a given max time.
* @param maxWait_ms max time to wait for true condition. Optional; defaults
* to 30 * 1000 ms (30 seconds).
* @param checkPeriod_ms period at which to try the condition. Optional; defaults
* to 100 ms.
* @param predicate the condition
* @param errorMessage message use in the {@link AssertionError}
* @throws Throwable on {@link AssertionError} or any other exception/error
*/
static public void waitForCondition(Integer maxWait_ms, Integer checkPeriod_ms,
Predicate predicate, String errorMessage) throws Throwable
{
waitForCondition(maxWait_ms, checkPeriod_ms, predicate, new Closure() {
public void execute(Object errorMessage)
{
fail((String)errorMessage);
}
}, errorMessage);
}
/** Blocks until a condition is true, running a closure if
* it does not become true during a given max time.
* @param maxWait_ms max time to wait for true condition. Optional; defaults
* to 30 * 1000 ms (30 seconds).
* @param checkPeriod_ms period at which to try the condition. Optional; defaults
* to 100 ms.
* @param predicate the condition
* @param closure closure to run
* @param argument argument for closure
* @throws Throwable on {@link AssertionError} or any other exception/error
*/
static public void waitForCondition(Integer maxWait_ms, Integer checkPeriod_ms,
Predicate predicate, Closure closure, Object argument) throws Throwable
{
if ( maxWait_ms == null )
maxWait_ms = 30 * 1000;
if ( checkPeriod_ms == null )
checkPeriod_ms = 100;
StopWatch stopWatch = new StopWatch();
stopWatch.start();
while ( !predicate.evaluate(null) ) {
Thread.sleep(checkPeriod_ms);
if ( stopWatch.getTime() > maxWait_ms ) {
closure.execute(argument);
}
}
}
/** Calls {@link #waitForVerify(Integer, Object)} with <code>null</code>
* for {@code maxWait_ms}
*/
static public void waitForVerify(Object easyMockProxy)
throws Throwable
{
waitForVerify(null, easyMockProxy);
}
/** Repeatedly calls {@link EasyMock#verify(Object[])} until it succeeds, or a
* max wait time has elapsed.
* @param maxWait_ms Max wait time. <code>null</code> defaults to 30s.
* @param easyMockProxy Proxy to call verify on
* @throws Throwable
*/
static public void waitForVerify(Integer maxWait_ms, Object easyMockProxy)
throws Throwable
{
if ( maxWait_ms == null )
maxWait_ms = 30 * 1000;
StopWatch stopWatch = new StopWatch();
stopWatch.start();
for(;;) {
try
{
verify(easyMockProxy);
break;
}
catch (AssertionError e)
{
if ( stopWatch.getTime() > maxWait_ms )
throw e;
Thread.sleep(100);
}
}
}
/** Returns a path to a directory in the temp dir with the name of the given
* class. This is useful for temporary test files.
* @param aClass test class for which to create dir
* @return the path
*/
static public String getTestDirPathForTestClass(Object object)
{
String filename = object instanceof Class ?
((Class)object).getName() :
object.getClass().getName();
return DRFileUtils.getTempDir() + File.separator +
filename;
}
static public byte[] createRandomByteArray(int bytesLength)
{
byte[] sourceBytes = new byte[bytesLength];
random.nextBytes(sourceBytes);
return sourceBytes;
}
/** Returns <code>true</code> if the given object is an EasyMock mock object
*/
static public boolean isEasyMockMock(Object object) {
try {
InvocationHandler invocationHandler = Proxy
.getInvocationHandler(object);
return invocationHandler.getClass().getName().contains("easymock");
} catch (IllegalArgumentException e) {
return false;
}
}
}
Listing 3:
@Test
public void testSomething() {
final AtomicBoolean called = new AtomicBoolean(false);
subject.setCallback(new SomeCallback() {
public void callback(Object arg) {
// check arg here
called.set(true);
}
});
subject.run();
assertTrue(called.get());
}
Hi using the following code its working...
onclick="window.open('privacy_policy.php','','width=1200,height=800,scrollbars=yes');
Previously i Entered like
onclick="window.open('privacy_policy.php','Window title','width=1200,height=800,scrollbars=yes');
Means Microsoft does not allow you to enter window name it should be blank in window.open
function...
Thanks, Nilesh Pangul
When plotting a plot using matplotlib:
How to remove the box of the legend?
plt.legend(frameon=False)
How to change the color of the border of the legend box?
leg = plt.legend()
leg.get_frame().set_edgecolor('b')
How to remove only the border of the box of the legend?
leg = plt.legend()
leg.get_frame().set_linewidth(0.0)
Here is another solution:
1) Download SumatraPDF (portable version) - https://www.sumatrapdfreader.org/download-free-pdf-viewer.html
2) Create a class library project and unzip the SumatraPDF.exe to the project directory root and unblock it.
3) Inside the project Properties, go to the Resoruces tab and add the exe as a file.
4) Add the following class to your library:
public class SumatraWrapper : IDisposable
{
private readonly FileInfo _tempFileForExe = null;
private readonly FileInfo _exe = null;
public SumatraWrapper()
{
_exe = ExtractExe();
}
public SumatraWrapper(FileInfo tempFileForExe)
: this()
{
_tempFileForExe = tempFileForExe ?? throw new ArgumentNullException(nameof(tempFileForExe));
}
private FileInfo ExtractExe()
{
string tempfile =
_tempFileForExe != null ?
_tempFileForExe.FullName :
Path.GetTempFileName() + ".exe";
FileInfo exe = new FileInfo(tempfile);
byte[] bytes = Properties.Resources.SumatraPDF;
using (FileStream fs = exe.OpenWrite())
{
fs.Write(bytes, 0, bytes.Length);
}
return exe;
}
public bool Print(FileInfo file, string printerName)
{
string arguments = $"-print-to \"{printerName}\" \"{file.FullName}\"";
ProcessStartInfo processStartInfo = new ProcessStartInfo(_exe.FullName, arguments)
{
CreateNoWindow = true
};
using (Process process = Process.Start(processStartInfo))
{
process.WaitForExit();
return process.ExitCode == 0;
}
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
try
{
File.Delete(_exe.FullName);
}
catch
{
}
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~PdfToPrinterWrapper() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
5) Enjoy printing pdf files from your code.
Use like this:
FileInfo file = new FileInfo(@"c:\Sandbox\dummy file.pdf");
SumatraWrapper pdfToPrinter =
new SumatraWrapper();
pdfToPrinter.Print(file, "My Printer");
You can try these:
function union(a, b) {
return a.concat(b).reduce(function(prev, cur) {
if (prev.indexOf(cur) === -1) prev.push(cur);
return prev;
}, []);
}
or
function union(a, b) {
return a.concat(b.filter(function(el) {
return a.indexOf(el) === -1;
}));
}
On macOS Mojave with Xcode 10.3, I got scary warnings from the gem
route with or without -n /usr/local/bin
:
xcodeproj's executable "xcodeproj" conflicts with /usr/local/bin/xcodeproj
Overwrite the executable? [yN]
What works for me is still Homebrew, just
brew install cocoapods
Changing only what's after hash - old browsers
document.location.hash = 'lookAtMeNow';
Changing full URL. Chrome, Firefox, IE10+
history.pushState('data to be passed', 'Title of the page', '/test');
The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use
history.replaceState('data to be passed', 'Title of the page', '/test');
Try running these in the console now!
Facebook has added test versions feature.
First, add a test version of your application: Create Test App
Then, change the Site URL to "http://localhost" under Website, and press Save Changes
That's all, but be careful: App ID and App Secret keys are different for the application and its test versions!
Here is a solution that lets you select the relations you want to include in your output as deep as you would like to go. NOTE: This is a complete re-write taking a dict/str as an arg rather than a list. fixes some stuff..
def deep_dict(self, relations={}):
"""Output a dict of an SA object recursing as deep as you want.
Takes one argument, relations which is a dictionary of relations we'd
like to pull out. The relations dict items can be a single relation
name or deeper relation names connected by sub dicts
Example:
Say we have a Person object with a family relationship
person.deep_dict(relations={'family':None})
Say the family object has homes as a relation then we can do
person.deep_dict(relations={'family':{'homes':None}})
OR
person.deep_dict(relations={'family':'homes'})
Say homes has a relation like rooms you can do
person.deep_dict(relations={'family':{'homes':'rooms'}})
and so on...
"""
mydict = dict((c, str(a)) for c, a in
self.__dict__.items() if c != '_sa_instance_state')
if not relations:
# just return ourselves
return mydict
# otherwise we need to go deeper
if not isinstance(relations, dict) and not isinstance(relations, str):
raise Exception("relations should be a dict, it is of type {}".format(type(relations)))
# got here so check and handle if we were passed a dict
if isinstance(relations, dict):
# we were passed deeper info
for left, right in relations.items():
myrel = getattr(self, left)
if isinstance(myrel, list):
mydict[left] = [rel.deep_dict(relations=right) for rel in myrel]
else:
mydict[left] = myrel.deep_dict(relations=right)
# if we get here check and handle if we were passed a string
elif isinstance(relations, str):
# passed a single item
myrel = getattr(self, relations)
left = relations
if isinstance(myrel, list):
mydict[left] = [rel.deep_dict(relations=None)
for rel in myrel]
else:
mydict[left] = myrel.deep_dict(relations=None)
return mydict
so for an example using person/family/homes/rooms... turning it into json all you need is
json.dumps(person.deep_dict(relations={'family':{'homes':'rooms'}}))
You can compile your code as Objective-C++ - the simplest way is to rename your .cpp as .mm. It will then compile properly if you include EAGLView.h
(you were getting so many errors because the C++ compiler didn't understand any of the Objective-C specific keywords), and you can (for the most part) mix Objective-C and C++ however you like.
libjpeg-dev is required to be able to process jpegs with pillow (or PIL), so you need to install it and then recompile pillow. It also seems that libjpeg8-dev is needed on Ubuntu 14.04
If you're still using PIL then you should really be using pillow these days though, so first pip uninstall PIL
before following these instructions to switch, or if you have a good reason for sticking with PIL then replace "pillow" with "PIL" in the below).
On Ubuntu:
# install libjpeg-dev with apt
sudo apt-get install libjpeg-dev
# if you're on Ubuntu 14.04, also install this
sudo apt-get install libjpeg8-dev
# reinstall pillow
pip install --no-cache-dir -I pillow
If that doesn't work, try one of the below, depending on whether you are on 64bit or 32bit Ubuntu.
For Ubuntu x64:
sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib
Or for Ubuntu 32bit:
sudo ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libfreetype.so.6 /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/
Then reinstall pillow:
pip install --no-cache-dir -I pillow
(Edits to include feedback from comments. Thanks Charles Offenbacher for pointing out this differs for 32bit, and t-mart for suggesting use of --no-cache-dir
).
You can alter a foreign key constraint with delete cascade option as shown below. This will delete chind table rows related to master table rows when deleted.
ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz
FOREIGN KEY (xyz)
REFERENCES ChildTable (xyz) ON DELETE CASCADE
The problem with jeet's answer is that you load all bytes of the image into a byte array, which will likely crash the app in low-end devices. Instead, I would first write the image to a file and read it using Apache's Base64InputStream class. Then you can create the Base64 string directly from the InputStream of that file. It will look like this:
//Don't forget the manifest permission to write files
final FileOutputStream fos = new FileOutputStream(yourFileHere);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
final InputStream is = new Base64InputStream( new FileInputStream(yourFileHere) );
//Now that we have the InputStream, we can read it and put it into the String
final StringWriter writer = new StringWriter();
IOUtils.copy(is , writer, encoding);
final String yourBase64String = writer.toString();
As you can see, the above solution works directly with streams instead, avoiding the need to load all the bytes into a variable, therefore making the memory footprint much lower and less likely to crash in low-end devices. There is still the problem that putting the Base64 string itself into a String variable is not a good idea, because, again, it might cause OutOfMemory errors. But at least we have cut the memory consumption by half by eliminating the byte array.
If you want to skip the write-to-a-file step, you have to convert the OutputStream to an InputStream, which is not so straightforward to do (you must use PipedInputStream but that is a little more complex as the two streams must always be in different threads).
By default VS is not made to run PHP, but you can do it with extensions:
You can install an add-on with the extension manager, PHP Tools for Visual Studio.
If you want to install it inside VS, go to Tools > Extension Manager > Online Gallery > Search for PHP where you will find PHP Tools (the link above) for Visual Studio. Also you have VS.Php for Visual Studio. Both are not free.
You have also a cool PHP compiler called Phalanger:
If I'm not mistaken, the code you wrote above is JavaScript (jQuery) and not PHP.
If you want cool standalone IDE's for PHP: (Free)
SQL Server stored procedure:
CREATE PROCEDURE [dbo].[INS_MEM_BASIC]
@na varchar(50),
@occ varchar(50),
@New_MEM_BASIC_ID int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Mem_Basic
VALUES (@na, @occ)
SELECT @New_MEM_BASIC_ID = SCOPE_IDENTITY()
END
C# code:
public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
// values 0 --> -99 are SQL reserved.
int new_MEM_BASIC_ID = -1971;
SqlConnection SQLconn = new SqlConnection(Config.ConnectionString);
SqlCommand cmd = new SqlCommand("INS_MEM_BASIC", SQLconn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter outPutVal = new SqlParameter("@New_MEM_BASIC_ID", SqlDbType.Int);
outPutVal.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outPutVal);
cmd.Parameters.Add("@na", SqlDbType.Int).Value = Mem_NA;
cmd.Parameters.Add("@occ", SqlDbType.Int).Value = Mem_Occ;
SQLconn.Open();
cmd.ExecuteNonQuery();
SQLconn.Close();
if (outPutVal.Value != DBNull.Value) new_MEM_BASIC_ID = Convert.ToInt32(outPutVal.Value);
return new_MEM_BASIC_ID;
}
I hope these will help to you ....
You can also use this if you want ...
public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
using (SqlConnection con=new SqlConnection(Config.ConnectionString))
{
int newID;
var cmd = "INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT CAST(scope_identity() AS int)";
using(SqlCommand cmd=new SqlCommand(cmd, con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
newID = (int)insertCommand.ExecuteScalar();
if (con.State == System.Data.ConnectionState.Open) con.Close();
return newID;
}
}
}
Another way
body {_x000D_
text-align: center;_x000D_
}_x000D_
form {_x000D_
display: inline-block;_x000D_
}
_x000D_
<body>_x000D_
<form>_x000D_
<input type="text" value="abc">_x000D_
</form>_x000D_
</body>
_x000D_
just use this:
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["1","2","3","4","5","6","7","8","9","10","11",],
datasets: [{
label: 'YOUR LABEL',
backgroundColor: [
"#566573",
"#99a3a4",
"#dc7633",
"#f5b041",
"#f7dc6f",
"#82e0aa",
"#73c6b6",
"#5dade2",
"#a569bd",
"#ec7063",
"#a5754a"
],
data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],
},]
},
//HERE COMES THE AXIS Y LABEL
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
});
</script>
This code recursively flattens out JSON objects.
I included my timing mechanism in the code and it gives me 1ms but I'm not sure if that's the most accurate one.
var new_json = [{
"name": "fatima",
"age": 25,
"neighbour": {
"name": "taqi",
"location": "end of the street",
"property": {
"built in": 1990,
"owned": false,
"years on market": [1990, 1998, 2002, 2013],
"year short listed": [], //means never
}
},
"town": "Mountain View",
"state": "CA"
},
{
"name": "qianru",
"age": 20,
"neighbour": {
"name": "joe",
"location": "opposite to the park",
"property": {
"built in": 2011,
"owned": true,
"years on market": [1996, 2011],
"year short listed": [], //means never
}
},
"town": "Pittsburgh",
"state": "PA"
}]
function flatten(json, flattened, str_key) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (json[key] instanceof Object && json[key] != "") {
flatten(json[key], flattened, str_key + "." + key);
} else {
flattened[str_key + "." + key] = json[key];
}
}
}
}
var flattened = {};
console.time('flatten');
flatten(new_json, flattened, "");
console.timeEnd('flatten');
for (var key in flattened){
console.log(key + ": " + flattened[key]);
}
Output:
flatten: 1ms
.0.name: fatima
.0.age: 25
.0.neighbour.name: taqi
.0.neighbour.location: end of the street
.0.neighbour.property.built in: 1990
.0.neighbour.property.owned: false
.0.neighbour.property.years on market.0: 1990
.0.neighbour.property.years on market.1: 1998
.0.neighbour.property.years on market.2: 2002
.0.neighbour.property.years on market.3: 2013
.0.neighbour.property.year short listed:
.0.town: Mountain View
.0.state: CA
.1.name: qianru
.1.age: 20
.1.neighbour.name: joe
.1.neighbour.location: opposite to the park
.1.neighbour.property.built in: 2011
.1.neighbour.property.owned: true
.1.neighbour.property.years on market.0: 1996
.1.neighbour.property.years on market.1: 2011
.1.neighbour.property.year short listed:
.1.town: Pittsburgh
.1.state: PA
The below made sense for 2013. However, now, I would use the :not()
selector as described below.
CSS can be overwritten.
DEMO: http://jsfiddle.net/persianturtle/J4SUb/
Use this:
.parent {
padding: 50px;
border: 1px solid black;
}
.parent span {
position: absolute;
top: 200px;
padding: 30px;
border: 10px solid green;
}
.parent:hover span {
border: 10px solid red;
}
.parent span:hover {
border: 10px solid green;
}
_x000D_
<a class="parent">
Parent text
<span>Child text</span>
</a>
_x000D_
Unfortunately, strptime()
can only handle the timezone configured by your OS, and then only as a time offset, really. From the documentation:
Support for the
%Z
directive is based on the values contained intzname
and whetherdaylight
is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).
strftime()
doesn't officially support %z
.
You are stuck with python-dateutil
to support timezone parsing, I am afraid.
do you try
[{"name":"myEnterprise", "departments":["HR"]}]
the square brace is the key point.
To bypass caching and avoid adding infinite timestamps to the image url, strip the previous timestamp before adding a new one, this is how I've done it.
//refresh the image every 60seconds
var xyro_refresh_timer = setInterval(xyro_refresh_function, 60000);
function xyro_refresh_function(){
//refreshes an image with a .xyro_refresh class regardless of caching
//get the src attribute
source = jQuery(".xyro_refresh").attr("src");
//remove previously added timestamps
source = source.split("?", 1);//turns "image.jpg?timestamp=1234" into "image.jpg" avoiding infinitely adding new timestamps
//prep new src attribute by adding a timestamp
new_source = source + "?timestamp=" + new Date().getTime();
//alert(new_source); //you may want to alert that during developement to see if you're getting what you wanted
//set the new src attribute
jQuery(".xyro_refresh").attr("src", new_source);
}
But what exactly is O(log n)
What it means precisely is "as n
tends towards infinity
, the time
tends towards a*log(n)
where a
is a constant scaling factor".
Or actually, it doesn't quite mean that; more likely it means something like "time
divided by a*log(n)
tends towards 1
".
"Tends towards" has the usual mathematical meaning from 'analysis': for example, that "if you pick any arbitrarily small non-zero constant k
, then I can find a corresponding value X
such that ((time/(a*log(n))) - 1)
is less than k
for all values of n
greater than X
."
In lay terms, it means that the equation for time may have some other components: e.g. it may have some constant startup time; but these other components pale towards insignificance for large values of n, and the a*log(n) is the dominating term for large n.
Note that if the equation were, for example ...
time(n) = a + blog(n) + cn + dnn
... then this would be O(n squared) because, no matter what the values of the constants a, b, c, and non-zero d, the d*n*n
term would always dominate over the others for any sufficiently large value of n.
That's what bit O notation means: it means "what is the order of dominant term for any sufficiently large n".
Solution posted by Denys S. in the question post:
I quite messed it up with c to c++ conversion (basically env
variable stuff), but I got it working with the following code for C++:
#include <string.h>
#include <stdio.h>
#include <jni.h>
jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){
jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);
const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
printf("%s\n", str);
return (*env)->NewStringUTF(env, str);
}
And next code for java methods:
public class MainActivity extends Activity {
private static String LIB_NAME = "thelib";
static {
System.loadLibrary(LIB_NAME);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textview);
tv.setText(this.getJniString());
}
// please, let me live even though I used this dark programming technique
public String messageMe(String text) {
System.out.println(text);
return text;
}
public native String getJniString();
}
I am not very good in grep. But your problem can be solved using AWK command. Just see
awk '/select/,/from/' *.sql
The above code will result from first occurence of select
till first sequence of from
. Now you need to verify whether returned statements are having customername
or not. For this you can pipe the result. And can use awk or grep again.
You can use git stash
. You have to specify --include-untracked
, otherwise you'll end up with the original problem.
git stash --include-untracked
Then just drop the last entry in the stash
git stash drop
You can make a handy-dandy alias for that, and call it git discard
for example:
git config --global alias.discard "! git stash -q --include-untracked && git stash drop -q"
To get a scrollbar for an ItemsControl
, you can host it in a ScrollViewer
like this:
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl>
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
</ItemsControl>
</ScrollViewer>
As far as I can tell there is no upper limit in 2008.
In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg
variable with
Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.
the code below fails with
REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.
However it appears these limitations have quietly been lifted. On 2008
DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681);
SET @y = REPLICATE(@y,92681);
SELECT LEN(@y)
Returns
8589767761
I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory
Running
select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid
Returned
internal_objects_alloc_page_co
------------------------------
2144456
so I presume this all just gets stored in LOB
pages in tempdb
with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681);
statement. The initial variable assignment to @y
and the LEN
calculation did not increase this.
The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE
method isn't supported for varchar(max) variables.
Addition
I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max)
and nvarchar(max) + varchar(max)
. Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
again. The script for that is below (may take a long time to run).
DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647);
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1) /*4294967294, 4294967292*/
DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823);
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2) /*2147483646, 4294967292*/
DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3) /*6442450940, 12884901880*/
/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test
simple way for new font awesome
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="txtSearch" >
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="fas fa-search"></i></button>
</div>
</div>
This worked for me:
def smallest_missing_positive_integer(A):
A.sort()
N = len(A)
now = A[0]
for i in range(1, N, 1):
next = A[i]
#check if there is no gap between 2 numbers and if positive
# "now + 1" is the "gap"
if (next > now + 1):
if now + 1 > 0:
return now + 1 #return the gap
now = next
return max(1, A[N-1] + 1) #if there is no positive number returns 1, otherwise the end of A+1
I had the same problem. I my case it was a program i've install that had destroyed the PATH env variable.
so check your PATH environment variable.
As far as the Python languages is concerned, _
has no special meaning. It is a valid identifier just like _foo
, foo_
or _f_o_o_
.
Any special meaning of _
is purely by convention. Several cases are common:
A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.
# iteration disregarding content
sum(1 for _ in some_iterable)
# unpacking disregarding specific elements
head, *_ = values
# function disregarding its argument
def callback(_): return True
Many REPLs/shells store the result of the last top-level expression to builtins._
.
The special identifier
_
is used in the interactive interpreter to store the result of the last evaluation; it is stored in thebuiltins
module. When not in interactive mode,_
has no special meaning and is not defined. [source]
Due to the way names are looked up, unless shadowed by a global or local _
definition the bare _
refers to builtins._
.
>>> 42
42
>>> f'the last answer is {_}'
'the last answer is 42'
>>> _
'the last answer is 42'
>>> _ = 4 # shadow ``builtins._`` with global ``_``
>>> 23
23
>>> _
4
Note: Some shells such as ipython
do not assign to builtins._
but special-case _
.
In the context internationalization and localization, _
is used as an alias for the primary translation function.
Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).
Summary (@Freek Wiekmeijer, @gtalarico) other's answer:
authentication
, then can access, otherwise 405 Not Allowed
authentication
=grant access
method are:
cookie
auth header
Basic xxx
Authorization xxx
cookie
in requests
to authcookie
in headers
cookie
by requests
's
session
to auto manage cookiesresponse.cookies
to manually set cookiesrequests
's session
auto manage cookiescurSession = requests.Session()
# all cookies received will be stored in the session object
payload={'username': "yourName",'password': "yourPassword"}
curSession.post(firstUrl, data=payload)
# internally return your expected cookies, can use for following auth
# internally use previously generated cookies, can access the resources
curSession.get(secondUrl)
curSession.get(thirdUrl)
requests
's response.cookies
payload={'username': "yourName",'password': "yourPassword"}
resp1 = requests.post(firstUrl, data=payload)
# manually pass previously returned cookies into following request
resp2 = requests.get(secondUrl, cookies= resp1.cookies)
resp3 = requests.get(thirdUrl, cookies= resp2.cookies)
The comparison with an epsilon value is what most people do (even in game programming).
You should change your implementation a little though:
bool AreSame(double a, double b)
{
return fabs(a - b) < EPSILON;
}
Edit: Christer has added a stack of great info on this topic on a recent blog post. Enjoy.
You can also write it like this:
let elem: any;
elem = $("div.printArea");
elem.printArea();
Parsing is the division of text in to a set of parts or tokens.
Other answers correctly talk about the Python ternary operator. I would like to complement by mentioning a scenario for which the ternary operator is often used but for which there is a better idiom. This is the scenario of using a default value.
Suppose we want to use option_value
with a default value if it is not set:
run_algorithm(option_value if option_value is not None else 10)
or, if option_value
is never set to a falsy value (0
, ""
, etc), simply
run_algorithm(option_value if option_value else 10)
However, in this case an ever better solution is simply to write
run_algorithm(option_value or 10)
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
Here is my answer that works just fine...
You should be able to get current Activity in this way... If you structure your app with a few Activities with many fragments and you want to keep track of what is your current Activity, it would take a lot of work though. My senario was I do have one Activity with multiple Fragments. So I can keep track of Current Activity through Application Object, which can store all of the current state of Global variables.
Here is a way. When you start your Activity, you store that Activity by Application.setCurrentActivity(getIntent()); This Application will store it. On your service class, you can simply do like Intent currentIntent = Application.getCurrentActivity(); getApplication().startActivity(currentIntent);
DESCRIBE FORMATTED <tablename>
or
DESCRIBE EXTENDED <tablename>
I prefer formatted because it is more human readable format
Just an example started from
history = model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10, verbose=0)
You can use
print(history.history.keys())
to list all data in history.
Then, you can print the history of validation loss like this:
print(history.history['val_loss'])
stdin.read(1)
will not return when you press one character - it will wait for '\n'. The problem is that the second character is buffered in standard input, and the moment you call another input - it will return immediately because it gets its input from buffer.
In the world of web development, the device pixel ratio (also called CSS Pixel Ratio) is what determines how a device's screen resolution is interpreted by the CSS.
A browser's CSS calculates a device's logical (or interpreted) resolution by the formula:
For example:
Apple iPhone 6s
When viewing a web page, the CSS will think the device has a 375x667 resolution screen and Media Queries will respond as if the screen is 375x667. But the rendered elements on the screen will be twice as sharp as an actual 375x667 screen because there are twice as many physical pixels in the physical screen.
Some other examples:
Samsung Galaxy S4
iPhone 5s
The reason that CSS pixel ratio was created is because as phones screens get higher resolutions, if every device still had a CSS pixel ratio of 1 then webpages would render too small to see.
A typical full screen desktop monitor is a roughly 24" at 1920x1080 resolution. Imagine if that monitor was shrunk down to about 5" but had the same resolution. Viewing things on the screen would be impossible because they would be so small. But manufactures are coming out with 1920x1080 resolution phone screens consistently now.
So the device pixel ratio was invented by phone makers so that they could continue to push the resolution, sharpness and quality of phone screens, without making elements on the screen too small to see or read.
Here is a tool that also tells you your current device's pixel density:
You can also try typecasting it with string.
package main
import "fmt"
func main() {
fmt.Println(string("Hello"[1]))
}
Not to be vague or anything but I think the type of 'file' you will be storing is one of the biggest determining factors. If you essentially talking about a large text field which could be stored as file my preference would be for db storage.
One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.
To echo elements of array properly, you can use the function, implode(separator, array)
Example:
implode(' ', $var)
result:
first name[1], last name[1]
first name[2], last name[2]
More examples from W3C.