Although display: flex;
has been suggested here, consider using display: grid;
now that it's widely supported. By default, the only child of a grid will entirely fill its parent.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0; /* Don't forget Safari */_x000D_
}_x000D_
_x000D_
#containment {_x000D_
display: grid;_x000D_
min-height: 100%;_x000D_
background: pink;_x000D_
}_x000D_
_x000D_
#containment-shadow-left {_x000D_
background: aqua;_x000D_
}
_x000D_
I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5
This makes me happy.
Try this: Live Demo
display: table
is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>
.
CSS:
#container {
background: #ccc;
display: table
}
#left, #right {
display: table-cell
}
#left {
width: 150px;
background: #f0f;
border: 5px dotted blue;
}
#right {
background: #aaa;
border: 3px solid #000
}
In my case, I named a column name type
and tried to set its value as UNPREPARED
. And I got an error message like this:
Caused by: api_1 | NameError: uninitialized constant UNPREPARED
In rails, column type
is reserved:
ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'UNPREPARED'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Pl ease rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Food.inheritance_column to use another column for that information
I was absolutely baffled by this problem. I had tried everything in this thread, and in others, but no matter what I did I could not change the color of the underline to anything other than the default blue.
I finally figured out what was going on. I was (incorrectly) using android.widget.EditText
when making a new instance (but the rest of my components were from the appcompat library). I should have used android.support.v7.widget.AppCompatEditText
. I replaced new EditText(this)
with new AppCompatEditText(this)
and the problem was instantly solved. It turns out, if you are actually using AppCompatEditText
, it will just respect the accentColor
from your theme (as mentioned in several comments above) and no additional configuration is necessary.
regexp_replace
UDF performs my task. Below is the definition and usage from apache Wiki.
regexp_replace(string INITIAL_STRING, string PATTERN, string REPLACEMENT):
This returns the string resulting from replacing all substrings in INITIAL_STRING
that match the java regular expression syntax defined in PATTERN
with instances of REPLACEMENT
,
e.g.: regexp_replace("foobar", "oo|ar", "")
returns fb
strtotime will work that out. the dates are just not the same and all in us-format.
<?php
$e1 = strtotime("2013-07-22T12:00:03Z");
echo date('y.m.d H:i', $e1);
echo "2013-07-22T12:00:03Z";
$e2 = strtotime("2013-07-23T18:18:15Z");
echo date ('y.m.d H:i', $e2);
echo "2013-07-23T18:18:15Z";
$e1 = strtotime("2013-07-21T23:57:04Z");
echo date ('y.m.d H:i', $e2);
echo "2013-07-21T23:57:04Z";
?>
$diff_min = ( strtotime( $day2 ) - strtotime( $day1 ) ) / 60 / 60;
$total_time = $diff_min;
You can try this one.
import java.io.*;
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
Consider the following if you run into any further problems, but I'm guessing that the above will work for you:
Antonio's answer
CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
is wrong; it may produce incorrect results!
For example, if "number" is 12345.67, the resulting string would be:
'12.346,67'
instead of
'12.345,67'
because FORMAT(number,0) rounds "number" up if fractional part is greater or equal than 0.5 (as it is in my example)!
What you COULD use is
CONCAT(REPLACE(FORMAT(FLOOR(number),0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
if your MySQL/MariaDB's FORMAT doesn't support "locale_name" (see MindStalker's post - Thx 4 that, pal). Note the FLOOR function I've added.
I just had to solve the same problem: json-encoding an entity ("User") having a One-To-Many Bidirectional Association to another Entity ("Location").
I tried several things and I think now I found the best acceptable solution. The idea was to use the same code as written by David, but somehow intercept the infinite recursion by telling the Normalizer to stop at some point.
I did not want to implement a custom normalizer, as this GetSetMethodNormalizer is a nice approach in my opinion (based on reflection etc.). So I've decided to subclass it, which is not trivial at first sight, because the method to say if to include a property (isGetMethod) is private.
But, one could override the normalize method, so I intercepted at this point, by simply unsetting the property that references "Location" - so the inifinite loop is interrupted.
In code it looks like this:
class GetSetMethodNormalizer extends \Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer {
public function normalize($object, $format = null)
{
// if the object is a User, unset location for normalization, without touching the original object
if($object instanceof \Leonex\MoveBundle\Entity\User) {
$object = clone $object;
$object->setLocations(new \Doctrine\Common\Collections\ArrayCollection());
}
return parent::normalize($object, $format);
}
}
This error can also occur in the normal situation when a database is starting or stopping. Normally on startup you can wait until the startup completes, then connect as usual. If the error persists, the service (on a Windows box) may be started without the database being started. This may be due to startup issues, or because the service is not configured to automatically start the database. In this case you will have to connect as sysdba and physically start the database using the "startup" command.
Edit: Just use Mime Detective
I use byte array sequences to determine the correct MIME type of a given file. The advantage of this over just looking at the file extension of the file name is that if a user were to rename a file to bypass certain file type upload restrictions, the file name extension would fail to catch this. On the other hand, getting the file signature via byte array will stop this mischievous behavior from happening.
Here is an example in C#:
public class MimeType
{
private static readonly byte[] BMP = { 66, 77 };
private static readonly byte[] DOC = { 208, 207, 17, 224, 161, 177, 26, 225 };
private static readonly byte[] EXE_DLL = { 77, 90 };
private static readonly byte[] GIF = { 71, 73, 70, 56 };
private static readonly byte[] ICO = { 0, 0, 1, 0 };
private static readonly byte[] JPG = { 255, 216, 255 };
private static readonly byte[] MP3 = { 255, 251, 48 };
private static readonly byte[] OGG = { 79, 103, 103, 83, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 };
private static readonly byte[] PDF = { 37, 80, 68, 70, 45, 49, 46 };
private static readonly byte[] PNG = { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 };
private static readonly byte[] RAR = { 82, 97, 114, 33, 26, 7, 0 };
private static readonly byte[] SWF = { 70, 87, 83 };
private static readonly byte[] TIFF = { 73, 73, 42, 0 };
private static readonly byte[] TORRENT = { 100, 56, 58, 97, 110, 110, 111, 117, 110, 99, 101 };
private static readonly byte[] TTF = { 0, 1, 0, 0, 0 };
private static readonly byte[] WAV_AVI = { 82, 73, 70, 70 };
private static readonly byte[] WMV_WMA = { 48, 38, 178, 117, 142, 102, 207, 17, 166, 217, 0, 170, 0, 98, 206, 108 };
private static readonly byte[] ZIP_DOCX = { 80, 75, 3, 4 };
public static string GetMimeType(byte[] file, string fileName)
{
string mime = "application/octet-stream"; //DEFAULT UNKNOWN MIME TYPE
//Ensure that the filename isn't empty or null
if (string.IsNullOrWhiteSpace(fileName))
{
return mime;
}
//Get the file extension
string extension = Path.GetExtension(fileName) == null
? string.Empty
: Path.GetExtension(fileName).ToUpper();
//Get the MIME Type
if (file.Take(2).SequenceEqual(BMP))
{
mime = "image/bmp";
}
else if (file.Take(8).SequenceEqual(DOC))
{
mime = "application/msword";
}
else if (file.Take(2).SequenceEqual(EXE_DLL))
{
mime = "application/x-msdownload"; //both use same mime type
}
else if (file.Take(4).SequenceEqual(GIF))
{
mime = "image/gif";
}
else if (file.Take(4).SequenceEqual(ICO))
{
mime = "image/x-icon";
}
else if (file.Take(3).SequenceEqual(JPG))
{
mime = "image/jpeg";
}
else if (file.Take(3).SequenceEqual(MP3))
{
mime = "audio/mpeg";
}
else if (file.Take(14).SequenceEqual(OGG))
{
if (extension == ".OGX")
{
mime = "application/ogg";
}
else if (extension == ".OGA")
{
mime = "audio/ogg";
}
else
{
mime = "video/ogg";
}
}
else if (file.Take(7).SequenceEqual(PDF))
{
mime = "application/pdf";
}
else if (file.Take(16).SequenceEqual(PNG))
{
mime = "image/png";
}
else if (file.Take(7).SequenceEqual(RAR))
{
mime = "application/x-rar-compressed";
}
else if (file.Take(3).SequenceEqual(SWF))
{
mime = "application/x-shockwave-flash";
}
else if (file.Take(4).SequenceEqual(TIFF))
{
mime = "image/tiff";
}
else if (file.Take(11).SequenceEqual(TORRENT))
{
mime = "application/x-bittorrent";
}
else if (file.Take(5).SequenceEqual(TTF))
{
mime = "application/x-font-ttf";
}
else if (file.Take(4).SequenceEqual(WAV_AVI))
{
mime = extension == ".AVI" ? "video/x-msvideo" : "audio/x-wav";
}
else if (file.Take(16).SequenceEqual(WMV_WMA))
{
mime = extension == ".WMA" ? "audio/x-ms-wma" : "video/x-ms-wmv";
}
else if (file.Take(4).SequenceEqual(ZIP_DOCX))
{
mime = extension == ".DOCX" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "application/x-zip-compressed";
}
return mime;
}
}
Notice I handled DOCX file types differently since DOCX is really just a ZIP file. In this scenario, I simply check the file extension once I verified that it has that sequence. This example is far from complete for some people, but you can easily add your own.
If you want to add more MIME types, you can get the byte array sequences of many different file types from here. Also, here is another good resource concerning file signatures.
What I do a lot of times if all else fails is step through several files of a particular type that I am looking for and look for a pattern in the byte sequence of the files. In the end, this is still basic verification and cannot be used for 100% proof of determining file types.
I just used:
import java.nio.file.Path;
import java.nio.file.Paths;
...
Path workingDirectory=Paths.get(".").toAbsolutePath();
CSRF protection
TYPES OF CSRF USAGE
IN FORM
<form>
@csrf
</form>
or
<input type="hidden" name="token" value="{{ form_token() }}" />
META TAG
<meta name="csrf-token" content="{{ csrf_token() }}">
AJAX
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
SESSION
use Illuminate\Http\Request;
Route::get('/token', function (Request $request) {
$token = $request->session()->token();
$token = csrf_token();
// ...
});
MIDDLEWARE
App\Providers\RouteServiceProvider
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
];
}
As an alternative (since I didn't know about jsbeautifier.org until now), I have used a bookmarklet that reenabled the decode button in Dean Edward's Packer.
I found the instructions and bookmarklet here.
here is the bookmarklet (in case the site is down)
javascript:for%20(i=0;i<document.forms.length;++i)%20{for(j=0;j<document.forms[i].elements.length;++j){document.forms[i].elements[j].removeAttribute(%22readonly%22);document.forms[i].elements[j].removeAttribute(%22disabled%22);}}
I have used pdf2image. A simple python library that works like charm.
First install poppler on non linux machine. You can just download the zip. Unzip in Program Files and add bin to Machine Path.
After that you can use pdf2image in python class like this:
from pdf2image import convert_from_path, convert_from_bytes
images_from_path = convert_from_path(
inputfile,
output_folder=outputpath,
grayscale=True, fmt='jpeg')
I am not good with python but was able to make exe of it. Later you may use the exe with file input and output parameter. I have used it in C# and things are working fine.
Image quality is good. OCR works fine.
kindly executed these commands.
pip install google
pip install google-core-api
will definitely solve your problem
If I'm understanding you correctly, you can simply use .ToString() to retrieve the name of the enum from the value (Assuming it's already cast as the Enum); If you had the naked int (lets say from a database or something) you can first cast it to the enum. Both methods below will get you the enum name.
AuthenticationMethod myCurrentSetting = AuthenticationMethod.FORMS;
Console.WriteLine(myCurrentSetting); // Prints: FORMS
string name = Enum.GetNames(typeof(AuthenticationMethod))[(int)myCurrentSetting-1];
Console.WriteLine(name); // Prints: FORMS
Keep in mind though, the second technique assumes you are using ints and your index is 1 based (not 0 based). The function GetNames also is quite heavy by comparison, you are generating a whole array each time it's called. As you can see in the first technique, .ToString() is actually called implicitly. Both of these are already mentioned in the answers of course, I'm just trying to clarify the differences between them.
The jar was compiled to be 1.6
compliant. That is why you get this error. Two resolutions:
1) Use Java 1.6
OR
2) Recompile the jar to be compliant for your environment 1.7
String str;
String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new FileWriter(path, true));
try
{
while(true)
{
System.out.println("Enter the text : ");
str = br.readLine();
if(str.equalsIgnoreCase("exit"))
break;
else
pw.println(str);
}
}
catch (Exception e)
{
//oh noes!
}
finally
{
pw.close();
}
this will do what you intend for..
Show this "long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text "
to
long text long text long ...
function cutString(text){
var wordsToCut = 5;
var wordsArray = text.split(" ");
if(wordsArray.length>wordsToCut){
var strShort = "";
for(i = 0; i < wordsToCut; i++){
strShort += wordsArray[i] + " ";
}
return strShort+"...";
}else{
return text;
}
};
While you cannot prevent orientation change from taking effect you can emulate no change as stated in other answers.
First detect device orientation or reorientation and, using JavaScript, add a class name to your wrapping element (in this example I use the body tag).
function deviceOrientation() {
var body = document.body;
switch(window.orientation) {
case 90:
body.classList = '';
body.classList.add('rotation90');
break;
case -90:
body.classList = '';
body.classList.add('rotation-90');
break;
default:
body.classList = '';
body.classList.add('portrait');
break;
}
}
window.addEventListener('orientationchange', deviceOrientation);
deviceOrientation();
Then if the device is landscape, use CSS to set the body width to the viewport height and the body height to the viewport width. And let’s set the transform origin while we’re at it.
@media screen and (orientation: landscape) {
body {
width: 100vh;
height: 100vw;
transform-origin: 0 0;
}
}
Now, reorient the body element and slide (translate) it into position.
body.rotation-90 {
transform: rotate(90deg) translateY(-100%);
}
body.rotation90 {
transform: rotate(-90deg) translateX(-100%);
}
this works well without any special function needed. Much easier to write with php as well. <input onclick="this.form.submit()"/>
Issue has been resolved after updating Android studio version to 3.3-rc2 or latest released version.
cr: @shadowsheep
have to change version under /gradle/wrapper/gradle-wrapper.properties. refer below url https://stackoverflow.com/a/56412795/7532946
can you check your config
file under ~/.aws/config
- you might have an invalid section called [myname], something like this (this is an example)
[default]
region=us-west-2
output=json
[myname]
region=us-east-1
output=text
Just remove the [myname] section (including all content for this profile) and you will be fine to run aws
cli again
If url contains a certen string, redirect to index.php . You need to match against the %{REQUEST_URI} variable to check if the url contains a certen string.
To redirect example.com/foo/bar to /index.php if the uri contains bar anywhere in the uri string , you can use this :
RewriteEngine on
RewriteCond %{REQUEST_URI} bar
RewriteRule ^ /index.php [L,R]
OCV goes out of its way to make sure you can't do this without knowing the element type, but if you want an easily codable but not-very-efficient way to read it type-agnostically, you can use something like
double val=mean(someMat(Rect(x,y,1,1)))[channel];
To do it well, you do have to know the type though. The at<> method is the safe way, but direct access to the data pointer is generally faster if you do it correctly.
Why so complicated? I think using system API can achieve the same result:
UIImage *largeImage;
CGFloat ratio = 0.4; // you want to get a new image that is 40% the size of large image.
UIImage *newImage = [UIImage imageWithCGImage:largeImage.CGImage
scale:1/ratio
orientation:largeImage.imageOrientation];
// notice the second argument, it is 1/ratio, not ratio.
The only gotcha is you should pass inverse of target ratio as the second argument, as according to the document the second parameter specifies the ratio of original image compared to the new scaled one.
try the following example. Image overlay with text on image. demo
<div class="thumbnail">
<img src="https://s3.amazonaws.com/discount_now_staging/uploads/ed964a11-e089-4c61-b927-9623a3fe9dcb/direct_uploader_2F50cc1daf-465f-48f0-8417-b04ac68a999d_2FN_19_jewelry.jpg" alt="..." />
<div class="caption post-content">
</div>
<div class="details">
<h3>Robots!</h3>
<p>Lorem ipsum dolor sit amet</p>
</div>
</div>
css
.post-content {
background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
opacity: 0.5;
top:0;
left:0;
min-width: 500px;
min-height: 500px;
position: absolute;
color: #ffffff;
}
.thumbnail{
position:relative;
}
.details {
position: absolute;
z-index: 2;
top: 0;
color: #ffffff;
}
Thinking this should do what you want:
list1.All(item => list2.Contains(item)) &&
list2.All(item => list1.Contains(item));
if you want it to be distinct, you could change it to:
list1.All(item => list2.Contains(item)) &&
list1.Distinct().Count() == list1.Count &&
list1.Count == list2.Count
All of these examples use an external module, but you can achieve the same result using just the datetime module, as also presented in this SO answer:
from datetime import datetime
from datetime import timezone
dt = datetime.now()
dt.replace(tzinfo=timezone.utc)
print(dt.replace(tzinfo=timezone.utc).isoformat())
'2017-01-12T22:11:31+00:00'
Fewer dependencies and no pytz issues.
NOTE: If you wish to use this with python3 and python2, you can use this as well for the timezone import (hardcoded for UTC):
try:
from datetime import timezone
utc = timezone.utc
except ImportError:
#Hi there python2 user
class UTC(tzinfo):
def utcoffset(self, dt):
return timedelta(0)
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return timedelta(0)
utc = UTC()
If you are using Python 3 then this is for you and it really works.
print(value , sep='',end ='', file = sys.stdout , flush = False)
RFC 7396: JSON Merge Patch (published four years after the question was posted) describes the best practices for a PATCH in terms of the format and processing rules.
In a nutshell, you submit an HTTP PATCH to a target resource with the application/merge-patch+json MIME media type and a body representing only the parts that you want to be changed/added/removed and then follow the below processing rules.
Rules:
If the provided merge patch contains members that do not appear within the target, those members are added.
If the target does contain the member, the value is replaced.
Null values in the merge patch are given special meaning to indicate the removal of existing values in the target.
Example test cases that illustrate the rules above (as seen in the appendix of that RFC):
ORIGINAL PATCH RESULT
--------------------------------------------
{"a":"b"} {"a":"c"} {"a":"c"}
{"a":"b"} {"b":"c"} {"a":"b",
"b":"c"}
{"a":"b"} {"a":null} {}
{"a":"b", {"a":null} {"b":"c"}
"b":"c"}
{"a":["b"]} {"a":"c"} {"a":"c"}
{"a":"c"} {"a":["b"]} {"a":["b"]}
{"a": { {"a": { {"a": {
"b": "c"} "b": "d", "b": "d"
} "c": null} }
} }
{"a": [ {"a": [1]} {"a": [1]}
{"b":"c"}
]
}
["a","b"] ["c","d"] ["c","d"]
{"a":"b"} ["c"] ["c"]
{"a":"foo"} null null
{"a":"foo"} "bar" "bar"
{"e":null} {"a":1} {"e":null,
"a":1}
[1,2] {"a":"b", {"a":"b"}
"c":null}
{} {"a": {"a":
{"bb": {"bb":
{"ccc": {}}}
null}}}
In iTunes 11 you can go to the view menu, and "Show Sidebar", this will give you the sidebar, that you can drag 'n drop to.
You'll drag 'n drop to the open area that will be near the bottom of the sidebar (I'm typically doing this with both an IPA and a provisioning profile). After you do that, there will be an apps menu that appears in the sidebar with your app in it. Click on that, and you'll see your application in the main view. You can then drag your application from there to your device. Below, please find a video (it's private, so you'll need the URL) that outlines the steps visually: http://youtube.com/watch?v=0ACq4CRpEJ8&feature=youtu.be
Using php from a shell script:
value="http://www.google.com"
encoded=$(php -r "echo rawurlencode('$value');")
# encoded = "http%3A%2F%2Fwww.google.com"
echo $(php -r "echo rawurldecode('$encoded');")
# returns: "http://www.google.com"
If you have multiple folders in your workspace, set up the search.exclude
on each folder. There's a drop-down next to WORKSPACE SETTINGS
.
If you have more complex requirements than just the top directory (eg ignore VCS dirs etc), you can also modify the list of directories to prevent os.walk recursing through them.
ie:
def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
dirs[:] = [d for d in dirs if is_good(d)]
for f in files:
do_stuff()
Note - be careful to mutate the list, rather than just rebind it. Obviously os.walk doesn't know about the external rebinding.
public void TakeScreenshot()
{
try
{
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile(@"D:\Screenshots\SeleniumTestingScreenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
New to Eclipse and Android development and this hung me up for quite a while. Here's a few things I was doing wrong that may help someone in the future:
import sys
out of hello function.'
should be escaped or should be surrouned by "
.python hello.py <some-number> <some-number>
in command line?import sys
def hello(a,b):
print "hello and that's your sum:", a + b
if __name__ == "__main__":
a = int(sys.argv[1])
b = int(sys.argv[2])
hello(a, b)
I think I have good solution how to fix problem like this - List => List with grouping by Something.a & Something.b. There is extended definition:
public class Test {
public static void test() {
class A {
private int a;
private int b;
private float c;
private float d;
public A(int a, int b, float c, float d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
List<A> list1 = new ArrayList<A>();
list1.addAll(Arrays.asList(new A(1, 2, 3, 4),
new A(2, 3, 4, 5),
new A(1, 2, 3, 4),
new A(2, 3, 4, 5),
new A(1, 2, 3, 4)));
Map<Integer, A> map = list1.stream()
.collect(HashMap::new, (m, v) -> m.put(
Objects.hash(v.a, v.b, v.c, v.d), v),
HashMap::putAll);
list1.clear();
list1.addAll(map.values());
System.out.println(list1);
}
}
class A, list1 it's just incoming data - magic is in the Objects.hash(...) :)
addEventListener
lets you set multiple handlers, but isn't supported in IE8 or lower.
IE does have attachEvent
, but it's not exactly the same.
var findObjectByLabel = function(obj, label)
{
var foundLabel=null;
if(obj.label === label)
{
return obj;
}
for(var i in obj)
{
if(Array.isArray(obj[i])==true)
{
for(var j=0;j<obj[i].length;j++)
{
foundLabel = findObjectByLabel(obj[i], label);
}
}
else if(typeof(obj[i]) == 'object')
{
if(obj.hasOwnProperty(i))
{
foundLabel = findObjectByLabel(obj[i], label);
}
}
if(foundLabel)
{
return foundLabel;
}
}
return null;
};
var x = findObjectByLabel(cars, "Sedan");
alert(JSON.stringify(x));
First I am afraid your question contains a little mistake. There is not method writeline in class Console. Instead class Console provides method writer() that returns PrintWriter. This print writer has println().
Now what is the difference between
System.console().writer().println("hello from console");
and
System.out.println("hello system out");
If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.
Here is an example I have just implemented.
import java.io.Console;
public class TestConsole {
public static void main(String[] args) {
Console console = System.console();
System.out.println("console=" + console);
console.writer().println("hello from console");
}
}
When I ran the application from command prompt I got the following:
$ java TestConsole
console=java.io.Console@93dcd
hello from console
but when I redirected the STDOUT to file...
$ java TestConsole >/tmp/test
Exception in thread "main" java.lang.NullPointerException
at TestConsole.main(TestConsole.java:8)
Line 8 is console.writer().println()
.
Here is the content of /tmp/test
console=null
I hope my explanations help.
Despite the imprecise nature of the question, here's my interpretive answer.
var html = [
'<div> A line</div>',
'<div> Add more lines</div>',
'<div> To the array as you need.</div>'
].join('');
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = html;
document.getElementById('posts').appendChild(div);
You can use the DataRowView to get the column index.
void OnRequestsGridRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var data = e.Row.DataItem as DataRowView;
// replace request name with a link
if (data.DataView.Table.Columns["Request Name"] != null)
{
// get the request name
string title = data["Request Name"].ToString();
// get the column index
int idx = data.Row.Table.Columns["Request Name"].Ordinal;
// ...
e.Row.Cells[idx].Controls.Clear();
e.Row.Cells[idx].Controls.Add(link);
}
}
}
The answers here got me close, but in 2016, I was able to write the following LINQ:
List<ObjectType> objectList = similarTypeList.Select(o =>
new ObjectType
{
PropertyOne = o.PropertyOne,
PropertyTwo = o.PropertyTwo,
PropertyThree = o.PropertyThree
}).ToList();
Try
rows = tabDelimitedTable.split("[" + newLine + "]");
This should solve the regex problem.
Also not that important but return type of
System.getProperty("line.separator")
is String so no need to call toString().
If you're having trouble with paths you can use
require Rails.root + 'db/migrate/20090408054532_add_foos.rb'
This:
doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));
should be:
doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));
LoadXml()
is for loading an XML string, not a file name.
On windows, in Git\etc\bash.bashrc
I use (at the end of the file)
a(){
git add $1
git status
}
and then in git bash simply write
$ a Config/
Both examples must work, but
svn merge -r UPREV:LOWREV .
undo range
svn merge -c -REV .
undo single revision
in this syntax - if current dir is WC and (as in must done after every merge) you'll commit results
Do you want to see logs?
The basic steps are:
Use a custom authentication provider
<bean id="myAuthenticationProvider" class="myProviderImplementation" scope="singleton">
...
</bean>
Make your custom provider return a custom UserDetails
implementation. This UserDetailsImpl
will have a getAuthorities()
like this:
public Collection<GrantedAuthority> getAuthorities() {
List<GrantedAuthority> permissions = new ArrayList<GrantedAuthority>();
for (GrantedAuthority role: roles) {
permissions.addAll(getPermissionsIncludedInRole(role));
}
return permissions;
}
Of course from here you could apply a lot of optimizations/customizations for your specific requirements.
#UBUNTU20
if you are opening this file as root, then type
root# visudo
the file will be opened, go to the line where you want to add/modifiy anything simply without any insert or i button pressed.
press ctrl + O
press ctrl + x
press enter
If you actually want your function to behave like the str()
built-in, but return an empty string when the argument is None, do this:
def xstr(s):
if s is None:
return ''
return str(s)
If you don't have access to getDefaultSharedPreferenes()
, you can use getSharedPreferences(name, mode)
instead, you just have to pass in the right name.
Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity
onCreate()
, and seeing what preferencesName
is.
String preferencesName = this.getPreferenceManager().getSharedPreferencesName();
The string should be something like com.example.projectname_preferences
. Hard code that somewhere in your project, and pass it in to getSharedPreferences()
and you should be good to go.
You can use node-php to run php with node js: https://github.com/mkschreder/node-php
If you absolutely want to combine integers and NaNs in a column, you can use the 'object' data type:
df['col'] = (
df['col'].fillna(0)
.astype(int)
.astype(object)
.where(df['col'].notnull())
)
This will replace NaNs with an integer (doesn't matter which), convert to int, convert to object and finally reinsert NaNs.
Use this in your li
style.
style="text-align-last: left;"
This way:
$instance = new Functions(); // create an instance (object) of functions class
$instance->filter($data); // now call it
To sum up, the quick linkedlist method:
List<String> llist = new LinkedList<String>(Arrays.asList(oldArray));
llist.remove(0);
If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat
class. It's very simple:
double d = 2.3d;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(d);
Which will output (depending on locale):
$2.30
Also, if currency isn't required (just the exact two decimal places) you can use this instead:
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String output = formatter.format(d);
Which will output 2.30
If you have Ruby(1.9+)
ruby -e 'Dir["*"].each{|x| File.rename(x,"PRE_"+x) }'
I meet this error when integrate modal bootstrap in angular.
This is my solution to solve this issue.
I share for whom concern.
First step you need install jquery
and bootstrap
by npm
command.
Second you need add declare var $ : any;
in component
And use can use $('#myModal').modal('hide');
on onSave() method
Demo https://stackblitz.com/edit/angular-model-bootstrap-close?file=src/app/app.component.ts
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
Just wanted to drop a note. I was having trouble formatting a text 4000 field that had a mind of its own and the text would seeming wrap (or not wrap) randomly on the report. When I updated the column using the replace chr(10) noted above. My report finally formatted as I wanted. Many Thanx!
Numpty here used SQL authentication
instead of Windows (correct)
when adding the login to SQL Server, which also gives you this error if you are using Windows auth.
Use a custom comparator:
Collections.sort(nodeList, new Comparator<DataNode>(){
public int compare(DataNode o1, DataNode o2){
if(o1.degree == o2.degree)
return 0;
return o1.degree < o2.degree ? -1 : 1;
}
});
Although you can access "inherited" static members through the inherited classes name, static members are not really inherited. This is in part why they can't be virtual or abstract and can't be overridden. In your example, if you declared a Base.Method(), the compiler will map a call to Inherited.Method() back to Base.Method() anyway. You might as well call Base.Method() explicitly. You can write a small test and see the result with Reflector.
So... if you can't inherit static members, and if static classes can contain only static members, what good would inheriting a static class do?
I will hijack this thread to point out that this error may also happen when target of Popen is not executable. Learnt it hard way when by accident I have had override a perfectly executable binary file with zip file.
I installed MVC4 via WPI and it helped me.
I found I needed to enable the SSL module in Apache (obviously prefix commands with sudo
if you are not running as root):
a2enmod ssl
then restart Apache:
/etc/init.d/apache2 restart
More details of SSL in Apache for Ubuntu / Debian here.
To install 32-bit Java on Windows 7 (64-bit OS + Machine). You can do:
1) Download JDK: http://javadl.sun.com/webapps/download/AutoDL?BundleId=58124
2) Download JRE: http://www.java.com/en/download/installed.jsp?jre_version=1.6.0_22&vendor=Sun+Microsystems+Inc.&os=Linux&os_version=2.6.41.4-1.fc15.i686
3) System variable create: C:\program files (x86)\java\jre6\bin\
4) Anywhere you type java -version
it use 32-bit on (64-bit). I have to use this because lots of third party libraries do not work with 64-bit. Java wake up from the hell, give us peach :P. Go-language is killer.
You need to use a raw string, double your slashes or use forward slashes instead:
r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'
In regular python strings, the \U
character combination signals a extended Unicode codepoint escape.
You can hit any number of other issues, for any of the recognised escape sequences, such as \a
or \t
or \x
, etc.
The dplyr package's select_if(
) function is an elegant solution:
library("dplyr")
select_if(x, is.numeric)
@start = 3
@records = 2
Select ID, Value
From
(SELECT ROW_NUMBER() OVER(ORDER BY ID) AS RowNum, ID,Value
From MyTable) as sub
Where sub.RowNum between @start and @start+@records
This is one way. there are a lot of others if you google SQL Paging.
Yes, there is a way to do it in XPath 1.0:
concat( substring($s1, 1, number($condition) * string-length($s1)), substring($s2, 1, number(not($condition)) * string-length($s2)) )
This relies on the concatenation of two mutually exclusive strings, the first one being empty if the condition is false (0 * string-length(...)
), the second one being empty if the condition is true. This is called "Becker's method", attributed to Oliver Becker.
In your case:
concat( substring( substring-before(//div[@id='head']/text(), ': '), 1, number( ends-with(//div[@id='head']/text(), ': ') ) * string-length(substring-before(//div [@id='head']/text(), ': ')) ), substring( //div[@id='head']/text(), 1, number(not( ends-with(//div[@id='head']/text(), ': ') )) * string-length(//div[@id='head']/text()) ) )
Though I would try to get rid of all the "//"
before.
Also, there is the possibility that //div[@id='head']
returns more than one node.
Just be aware of that — using //div[@id='head'][1]
is more defensive.
The simplest way is to generate a random nuber between 0-1 then strech it by multiplying, and shifting it.
So yo would multiply by (x-y) so the result is in the range of 0 to x-y,
Then add x and you get the random number between x and y.
To get a five multiplier use rounding. If this is unclear let me know and I'll add code snippets.
I got same error because I was trying to run on
XXX-Macmini:Python-Project XXX.XXX$ from classDemo import MyClass
from: can't read /var/mail/classDemo
To solve this, type command python and when you get these >>> then run any python commands
>>>from classDemo import MyClass
>>>f = MyClass()
I had the same problem and I solved it like this, by taking the original data frame without row names and adding them later
SFIo <- as.matrix(apply(SFI[,-1],2,as.numeric))
row.names(SFIo) <- SFI[,1]
Collection c;
Iterator iter = c.iterator();
Object first = iter.next();
(This is the closest you'll get to having the "first" element of a Set
. You should realize that it has absolutely no meaning for most implementations of Set
. This may have meaning for LinkedHashSet and TreeSet, but not for HashSet.)
In my case (running the server locally on windows) I needed to clean the cache after changing the httpd.conf file.
\modules\apache\bin> ./htcacheclean.exe -t
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Log.d(TAG, "Permission granted");
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
100);
}
fab.setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.refer_pic);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(requireActivity().getContentResolver(),
b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
share.putExtra(Intent.EXTRA_TEXT, "Here is text");
startActivity(Intent.createChooser(share, "Share via"));
});
Initially my repo said "Already up to date."
MINGW64 (feature/Issue_123)
$ git merge develop
Output:
Already up to date.
But the code is not up to date & it is showing some differences in some files.
MINGW64 (feature/Issue_123)
$ git diff develop
Output:
diff --git
a/src/main/database/sql/additional/pkg_etl.sql
b/src/main/database/sql/additional/pkg_etl.sql
index ba2a257..1c219bb 100644
--- a/src/main/database/sql/additional/pkg_etl.sql
+++ b/src/main/database/sql/additional/pkg_etl.sql
However, merging fixes it.
MINGW64 (feature/Issue_123)
$ git merge origin/develop
Output:
Updating c7c0ac9..09959e3
Fast-forward
3 files changed, 157 insertions(+), 92 deletions(-)
Again I have confirmed this by using diff
command.
MINGW64 (feature/Issue_123)
$ git diff develop
No differences in the code now!
The problem here, as explained in other comments, is that the pointer is being dereference without being properly initialized. Operating systems like Linux keep the lowest addresses (eg first 32MB: 0x00_0000 -0x200_0000) out of the virtual address space of a process. This is done because dereferencing zeroed non-initialized pointers is a common mistake, like in this case. So when this type of mistake happens, instead of actually reading a random variable that happens to be at address 0x0 (but not the memory address the pointer would be intended for if initialized properly), the pointer would be reading from a memory address outside of the process's virtual address space. This causes a page fault, which results in a segmentation fault, and a signal is sent to the process to kill it. That's why you are getting the access violation error.
Related to Eugen's answer, you can solve this particular case by creating a wrapper POJO object that contains a Collection<COrder>
as its member variable. This will properly guide Jackson to place the actual Collection
data inside the POJO's member variable and produce the JSON you are looking for in the API request.
Example:
public class ApiRequest {
@JsonProperty("collection")
private Collection<COrder> collection;
// getters
}
Then set the parameter type of COrderRestService.postOrder()
to be your new ApiRequest
wrapper POJO instead of Collection<COrder>
.
Also try changing from this:
SELECT * FROM table WHERE Contains(Column, "test") > 0;
To this:
SELECT * FROM table WHERE Contains(Column, '"*test*"') > 0;
The former will find records with values like "this is a test" and "a test-case is the plan".
The latter will also find records with values like "i am testing this" and "this is the greatest".
Try wrapping whatever you want to print out in parentheses:
Write-Host ($assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner)
Your code is being interpreted as many parameters being passed to Write-Host
. Wrapping it up inside parentheses will concatenate the values and then pass the resulting value as a single parameter.
do like
<input name="name" id="name" type="text" value="Name"
onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>
and js
function fillField(input,val) {
if(input.value == "")
input.value=val;
};
function clearField(input,val) {
if(input.value == val)
input.value="";
};
here is a demo fiddle of the same
The app token can be found from this url.
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
In C#/.NET 3.5 you could write a little program to do:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
string controller = context.ConnectedServer;
Console.WriteLine( "Domain Controller:" + controller );
}
This will list all the users in the current domain:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal searchPrincipal = new UserPrincipal(context))
{
using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
{
foreach (UserPrincipal principal in searcher.FindAll())
{
Console.WriteLine( principal.SamAccountName);
}
}
}
}
var str = "How are you doing today?";
var res = str.split(" ");
Here the variable "res" is kind of array.
You can also take this explicity by declaring it as
var res[]= str.split(" ");
Now you can access the individual words of the array. Suppose you want to access the third element of the array you can use it by indexing array elements.
var FirstElement= res[0];
Now the variable FirstElement contains the value 'How'
You can use in Content-security-policy add "img-src 'self' data:;" And Use outline CSS.Don't use Inline CSS.It's secure from attackers.
Or you can do it like this!
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
# Iterate through the list
for words in elements:
# Does this element belong in the resulting list?
if i <= len(elements):
# Add this element to the resulting list
new_list.append(elements[i])
# Increment i
i += 2
return new_list
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []
You can write
i = 5 + tup()[0]
Tuples can be indexed just like lists.
The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.
Checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is checked.
if (isChecked) {
//password is visible
PasswordField.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
} else {
//password gets hided
passwordField.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
During development, adding a quick
assert False, value
can help diagnose problems in views or anywhere else, without the need to use a debugger.
Below are some important differences in promises & Observables.
Promise
Observable
For better understanding refer to the https://stackblitz.com/edit/observable-vs-promises
i wrote this sp to create automatically the schema with all things, pk, fk, partitions, constraints... I wrote it to run in same sp.
IMPORTANT!! before exec
create type TableType as table (ObjectID int)
here the SP:
create PROCEDURE [dbo].[util_ScriptTable]
@DBName SYSNAME
,@schema sysname
,@TableName SYSNAME
,@IncludeConstraints BIT = 1
,@IncludeIndexes BIT = 1
,@NewTableSchema sysname
,@NewTableName SYSNAME = NULL
,@UseSystemDataTypes BIT = 0
,@script varchar(max) output
AS
BEGIN try
if not exists (select * from sys.types where name = 'TableType')
create type TableType as table (ObjectID int)--drop type TableType
declare @sql nvarchar(max)
DECLARE @MainDefinition TABLE (FieldValue VARCHAR(200))
--DECLARE @DBName SYSNAME
DECLARE @ClusteredPK BIT
DECLARE @TableSchema NVARCHAR(255)
--SET @DBName = DB_NAME(DB_ID())
SELECT @TableName = name FROM sysobjects WHERE id = OBJECT_ID(@TableName)
DECLARE @ShowFields TABLE (FieldID INT IDENTITY(1,1)
,DatabaseName VARCHAR(100)
,TableOwner VARCHAR(100)
,TableName VARCHAR(100)
,FieldName VARCHAR(100)
,ColumnPosition INT
,ColumnDefaultValue VARCHAR(100)
,ColumnDefaultName VARCHAR(100)
,IsNullable BIT
,DataType VARCHAR(100)
,MaxLength varchar(10)
,NumericPrecision INT
,NumericScale INT
,DomainName VARCHAR(100)
,FieldListingName VARCHAR(110)
,FieldDefinition CHAR(1)
,IdentityColumn BIT
,IdentitySeed INT
,IdentityIncrement INT
,IsCharColumn BIT
,IsComputed varchar(255))
DECLARE @HoldingArea TABLE(FldID SMALLINT IDENTITY(1,1)
,Flds VARCHAR(4000)
,FldValue CHAR(1) DEFAULT(0))
DECLARE @PKObjectID TABLE(ObjectID INT)
DECLARE @Uniques TABLE(ObjectID INT)
DECLARE @HoldingAreaValues TABLE(FldID SMALLINT IDENTITY(1,1)
,Flds VARCHAR(4000)
,FldValue CHAR(1) DEFAULT(0))
DECLARE @Definition TABLE(DefinitionID SMALLINT IDENTITY(1,1)
,FieldValue VARCHAR(200))
set @sql=
'
use '+@DBName+'
SELECT distinct DB_NAME()
,inf.TABLE_SCHEMA
,inf.TABLE_NAME
,''[''+inf.COLUMN_NAME+'']'' as COLUMN_NAME
,CAST(inf.ORDINAL_POSITION AS INT)
,inf.COLUMN_DEFAULT
,dobj.name AS ColumnDefaultName
,CASE WHEN inf.IS_NULLABLE = ''YES'' THEN 1 ELSE 0 END
,inf.DATA_TYPE
,case inf.CHARACTER_MAXIMUM_LENGTH when -1 then ''max'' else CAST(inf.CHARACTER_MAXIMUM_LENGTH AS varchar) end--CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
,CAST(inf.NUMERIC_PRECISION AS INT)
,CAST(inf.NUMERIC_SCALE AS INT)
,inf.DOMAIN_NAME
,inf.COLUMN_NAME + '',''
,'''' AS FieldDefinition
--caso di viste, dà come campo identity ma nn dà i valori, quindi lo ignoro
,CASE WHEN ic.object_id IS not NULL and ic.seed_value is not null THEN 1 ELSE 0 END AS IdentityColumn--CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
,CASE WHEN c.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn
,cc.definition
from (select schema_id,object_id,name from sys.views union all select schema_id,object_id,name from sys.tables)t
--sys.tables t
join sys.schemas s on t.schema_id=s.schema_id
JOIN sys.columns c ON t.object_id=c.object_id --AND s.schema_id=c.schema_id
LEFT JOIN sys.identity_columns ic ON t.object_id=ic.object_id AND c.column_id=ic.column_id
left JOIN sys.types st ON st.system_type_id=c.system_type_id and st.principal_id=t.object_id--COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = c.default_object_id AND dobj.type = ''D''
left join sys.computed_columns cc on t.object_id=cc.object_id and c.column_id=cc.column_id
join INFORMATION_SCHEMA.COLUMNS inf on t.name=inf.TABLE_NAME
and s.name=inf.TABLE_SCHEMA
and c.name=inf.COLUMN_NAME
WHERE inf.TABLE_NAME = @TableName and inf.TABLE_SCHEMA=@schema
ORDER BY inf.ORDINAL_POSITION
'
print @sql
INSERT INTO @ShowFields( DatabaseName
,TableOwner
,TableName
,FieldName
,ColumnPosition
,ColumnDefaultValue
,ColumnDefaultName
,IsNullable
,DataType
,MaxLength
,NumericPrecision
,NumericScale
,DomainName
,FieldListingName
,FieldDefinition
,IdentityColumn
,IdentitySeed
,IdentityIncrement
,IsCharColumn
,IsComputed)
exec sp_executesql @sql,
N'@TableName varchar(50),@schema varchar(50)',
@TableName=@TableName,@schema=@schema
/*
SELECT @DBName--DB_NAME()
,TABLE_SCHEMA
,TABLE_NAME
,COLUMN_NAME
,CAST(ORDINAL_POSITION AS INT)
,COLUMN_DEFAULT
,dobj.name AS ColumnDefaultName
,CASE WHEN c.IS_NULLABLE = 'YES' THEN 1 ELSE 0 END
,DATA_TYPE
,CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
,CAST(NUMERIC_PRECISION AS INT)
,CAST(NUMERIC_SCALE AS INT)
,DOMAIN_NAME
,COLUMN_NAME + ','
,'' AS FieldDefinition
,CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
,CASE WHEN st.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn
FROM INFORMATION_SCHEMA.COLUMNS c
JOIN sys.columns sc ON c.TABLE_NAME = OBJECT_NAME(sc.object_id) AND c.COLUMN_NAME = sc.Name
LEFT JOIN sys.identity_columns ic ON c.TABLE_NAME = OBJECT_NAME(ic.object_id) AND c.COLUMN_NAME = ic.Name
JOIN sys.types st ON COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = sc.default_object_id AND dobj.type = 'D'
WHERE c.TABLE_NAME = @TableName
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION
*/
SELECT TOP 1 @TableSchema = TableOwner FROM @ShowFields
INSERT INTO @HoldingArea (Flds) VALUES('(')
INSERT INTO @Definition(FieldValue)VALUES('CREATE TABLE ' + CASE WHEN @NewTableName IS NOT NULL THEN @DBName + '.' + @NewTableSchema + '.' + @NewTableName ELSE @DBName + '.' + @TableSchema + '.' + @TableName END)
INSERT INTO @Definition(FieldValue)VALUES('(')
INSERT INTO @Definition(FieldValue)
SELECT CHAR(10) + FieldName + ' ' +
--CASE WHEN DomainName IS NOT NULL AND @UseSystemDataTypes = 0 THEN DomainName + CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END ELSE UPPER(DataType) +CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')' ELSE '' END +CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')' ELSE '' END +CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END +CASE WHEN ColumnDefaultName IS NOT NULL AND @IncludeConstraints = 1 THEN 'CONSTRAINT [' + ColumnDefaultName + '] DEFAULT' + UPPER(ColumnDefaultValue) ELSE '' END END + CASE WHEN FieldID = (SELECT MAX(FieldID) FROM @ShowFields) THEN '' ELSE ',' END
CASE WHEN DomainName IS NOT NULL AND @UseSystemDataTypes = 0 THEN DomainName +
CASe WHEN IsNullable = 1 THEN ' NULL '
ELSE ' NOT NULL '
END
ELSE
case when IsComputed is null then
UPPER(DataType) +
CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')'
ELSE
CASE WHEN DataType = 'numeric' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')'
ELSE
CASE WHEN DataType = 'decimal' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')'
ELSE ''
end
end
END +
CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')'
ELSE ''
END +
CASE WHEN IsNullable = 1 THEN ' NULL '
ELSE ' NOT NULL '
END +
CASE WHEN ColumnDefaultName IS NOT NULL AND @IncludeConstraints = 1 THEN 'CONSTRAINT [' + replace(ColumnDefaultName,@TableName,@NewTableName) + '] DEFAULT' + UPPER(ColumnDefaultValue)
ELSE ''
END
else
' as '+IsComputed+' '
end
END +
CASE WHEN FieldID = (SELECT MAX(FieldID) FROM @ShowFields) THEN ''
ELSE ','
END
FROM @ShowFields
IF @IncludeConstraints = 1
BEGIN
set @sql=
'
use '+@DBName+'
SELECT distinct '',CONSTRAINT ['' + @NewTableName+''_''+replace(name,@TableName,'''') + ''] FOREIGN KEY ('' + ParentColumns + '') REFERENCES ['' + ReferencedObject + '']('' + ReferencedColumns + '')''
FROM ( SELECT ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
, REVERSE(SUBSTRING(REVERSE(( SELECT cp.name + '',''
FROM sys.foreign_key_columns fkc
JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('''') )), 2, 8000)) ParentColumns,
REVERSE(SUBSTRING(REVERSE(( SELECT cr.name + '',''
FROM sys.foreign_key_columns fkc
JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('''') )), 2, 8000)) ReferencedColumns
FROM sys.foreign_keys fk
inner join sys.schemas s on fk.schema_id=s.schema_id and s.name=@schema) a
WHERE ParentObject = @TableName
'
print @sql
INSERT INTO @Definition(FieldValue)
exec sp_executesql @sql,
N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50)',
@TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema
/*
SELECT ',CONSTRAINT [' + name + '] FOREIGN KEY (' + ParentColumns + ') REFERENCES [' + ReferencedObject + '](' + ReferencedColumns + ')'
FROM ( SELECT ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
, REVERSE(SUBSTRING(REVERSE(( SELECT cp.name + ','
FROM sys.foreign_key_columns fkc
JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('') )), 2, 8000)) ParentColumns,
REVERSE(SUBSTRING(REVERSE(( SELECT cr.name + ','
FROM sys.foreign_key_columns fkc
JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('') )), 2, 8000)) ReferencedColumns
FROM sys.foreign_keys fk ) a
WHERE ParentObject = @TableName
*/
set @sql=
'
use '+@DBName+'
SELECT distinct '',CONSTRAINT ['' + @NewTableName+''_''+replace(c.name,@TableName,'''') + ''] CHECK '' + definition
FROM sys.check_constraints c join sys.schemas s on c.schema_id=s.schema_id and s.name=@schema
WHERE OBJECT_NAME(parent_object_id) = @TableName
'
print @sql
INSERT INTO @Definition(FieldValue)
exec sp_executesql @sql,
N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50)',
@TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema
/*
SELECT ',CONSTRAINT [' + name + '] CHECK ' + definition FROM sys.check_constraints
WHERE OBJECT_NAME(parent_object_id) = @TableName
*/
set @sql=
'
use '+@DBName+'
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
WHERE OBJECT_NAME(parent_object_id) = @TableName AND i.type = 1 AND is_primary_key = 1
'
print @sql
INSERT INTO @PKObjectID(ObjectID)
exec sp_executesql @sql,
N'@TableName varchar(50),@schema varchar(50)',
@TableName=@TableName,@schema=@schema
/*
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE OBJECT_NAME(parent_object_id) = @TableName AND i.type = 1 AND is_primary_key = 1
*/
set @sql=
'
use '+@DBName+'
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
WHERE OBJECT_NAME(parent_object_id) = @TableName AND i.type = 2 AND is_primary_key = 0 AND is_unique_constraint = 1
'
print @sql
INSERT INTO @Uniques(ObjectID)
exec sp_executesql @sql,
N'@TableName varchar(50),@schema varchar(50)',
@TableName=@TableName,@schema=@schema
/*
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE OBJECT_NAME(parent_object_id) = @TableName AND i.type = 2 AND is_primary_key = 0 AND is_unique_constraint = 1
*/
SET @ClusteredPK = CASE WHEN @@ROWCOUNT > 0 THEN 1 ELSE 0 END
declare @t TableType
insert @t select * from @PKObjectID
declare @u TableType
insert @u select * from @Uniques
set @sql=
'
use '+@DBName+'
SELECT distinct '',CONSTRAINT '' + @NewTableName+''_''+replace(cco.name,@TableName,'''') + CASE type WHEN ''PK'' THEN '' PRIMARY KEY '' + CASE WHEN pk.ObjectID IS NULL THEN '' NONCLUSTERED '' ELSE '' CLUSTERED '' END WHEN ''UQ'' THEN '' UNIQUE '' END + CASE WHEN u.ObjectID IS NOT NULL THEN '' NONCLUSTERED '' ELSE '''' END
+ ''(''+REVERSE(SUBSTRING(REVERSE(( SELECT c.name + + CASE WHEN cc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''
FROM sys.key_constraints ccok
LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id
LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE i.object_id = ccok.parent_object_id AND ccok.object_id = cco.object_id
order by key_ordinal FOR XML PATH(''''))), 2, 8000)) + '')''
FROM sys.key_constraints cco
inner join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
LEFT JOIN @U u ON cco.object_id = u.objectID
LEFT JOIN @t pk ON cco.object_id = pk.ObjectID
WHERE OBJECT_NAME(cco.parent_object_id) = @TableName
'
print @sql
INSERT INTO @Definition(FieldValue)
exec sp_executesql @sql,
N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50),@t TableType readonly,@u TableType readonly',
@TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema,@t=@t,@u=@u
/*
SELECT ',CONSTRAINT ' + name + CASE type WHEN 'PK' THEN ' PRIMARY KEY ' + CASE WHEN pk.ObjectID IS NULL THEN ' NONCLUSTERED ' ELSE ' CLUSTERED ' END WHEN 'UQ' THEN ' UNIQUE ' END + CASE WHEN u.ObjectID IS NOT NULL THEN ' NONCLUSTERED ' ELSE '' END
+ '(' +REVERSE(SUBSTRING(REVERSE(( SELECT c.name + + CASE WHEN cc.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END + ','
FROM sys.key_constraints ccok
LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id
LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE i.object_id = ccok.parent_object_id AND ccok.object_id = cco.object_id FOR XML PATH(''))), 2, 8000)) + ')'
FROM sys.key_constraints cco
LEFT JOIN @PKObjectID pk ON cco.object_id = pk.ObjectID
LEFT JOIN @Uniques u ON cco.object_id = u.objectID
WHERE OBJECT_NAME(cco.parent_object_id) = @TableName
*/
END
INSERT INTO @Definition(FieldValue) VALUES(')')
set @sql=
'
use '+@DBName+'
select '' on '' + d.name + ''([''+c.name+''])''
from sys.tables t join sys.indexes i on(i.object_id = t.object_id and i.index_id < 2)
join sys.index_columns ic on(ic.partition_ordinal > 0 and ic.index_id = i.index_id and ic.object_id = t.object_id)
join sys.columns c on(c.object_id = ic.object_id and c.column_id = ic.column_id)
join sys.schemas s on t.schema_id=s.schema_id
join sys.data_spaces d on i.data_space_id=d.data_space_id
where t.name=@TableName and s.name=@schema
order by key_ordinal
'
print 'x'
print @sql
INSERT INTO @Definition(FieldValue)
exec sp_executesql @sql,
N'@TableName varchar(50),@schema varchar(50)',
@TableName=@TableName,@schema=@schema
IF @IncludeIndexes = 1
BEGIN
set @sql=
'
use '+@DBName+'
SELECT distinct '' CREATE '' + i.type_desc + '' INDEX ['' + replace(i.name COLLATE SQL_Latin1_General_CP1_CI_AS,@TableName,@NewTableName) + ''] ON '+@DBName+'.'+@NewTableSchema+'.'+@NewTableName+' (''
+ REVERSE(SUBSTRING(REVERSE(( SELECT name + CASE WHEN sc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE t.name=@TableName AND sc.object_id = i.object_id AND sc.index_id = i.index_id
and is_included_column=0
ORDER BY key_ordinal ASC FOR XML PATH('''') )), 2, 8000)) + '')''+
ISNULL( '' include (''+REVERSE(SUBSTRING(REVERSE(( SELECT name + '',''
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE t.name=@TableName AND sc.object_id = i.object_id AND sc.index_id = i.index_id
and is_included_column=1
ORDER BY key_ordinal ASC FOR XML PATH('''') )), 2, 8000))+'')'' ,'''')+''''
FROM sys.indexes i join sys.tables t on i.object_id=t.object_id
join sys.schemas s on t.schema_id=s.schema_id
AND CASE WHEN @ClusteredPK = 1 AND is_primary_key = 1 AND i.type = 1 THEN 0 ELSE 1 END = 1 AND is_unique_constraint = 0 AND is_primary_key = 0
where t.name=@TableName and s.name=@schema
'
print @sql
INSERT INTO @Definition(FieldValue)
exec sp_executesql @sql,
N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50), @ClusteredPK bit',
@TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema,@ClusteredPK=@ClusteredPK
END
/*
SELECT 'CREATE ' + type_desc + ' INDEX [' + [name] COLLATE SQL_Latin1_General_CP1_CI_AS + '] ON [' + OBJECT_NAME(object_id) + '] (' + REVERSE(SUBSTRING(REVERSE(( SELECT name + CASE WHEN sc.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END + ','
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE OBJECT_NAME(sc.object_id) = @TableName AND sc.object_id = i.object_id AND sc.index_id = i.index_id
ORDER BY index_column_id ASC FOR XML PATH('') )), 2, 8000)) + ')'
FROM sys.indexes i
WHERE OBJECT_NAME(object_id) = @TableName
AND CASE WHEN @ClusteredPK = 1 AND is_primary_key = 1 AND type = 1 THEN 0 ELSE 1 END = 1 AND is_unique_constraint = 0 AND is_primary_key = 0
*/
INSERT INTO @MainDefinition(FieldValue)
SELECT FieldValue FROM @Definition
ORDER BY DefinitionID ASC
----------------------------------
--SELECT FieldValue+'' FROM @MainDefinition FOR XML PATH('')
set @script='use '+@DBName+' '+(SELECT FieldValue+'' FROM @MainDefinition FOR XML PATH(''))
--declare @q varchar(max)
--set @q=(select replace((SELECT FieldValue FROM @MainDefinition FOR XML PATH('')),'</FieldValue>',''))
--set @script=(select REPLACE(@q,'<FieldValue>',''))
--drop type TableType
END try
-- ##############################################################################################################################################################################
BEGIN CATCH
BEGIN
-- INIZIO Procedura in errore =========================================================================================================================================================
PRINT '***********************************************************************************************************************************************************'
PRINT 'ErrorNumber : ' + CAST(ERROR_NUMBER() AS NVARCHAR(MAX))
PRINT 'ErrorSeverity : ' + CAST(ERROR_SEVERITY() AS NVARCHAR(MAX))
PRINT 'ErrorState : ' + CAST(ERROR_STATE() AS NVARCHAR(MAX))
PRINT 'ErrorLine : ' + CAST(ERROR_LINE() AS NVARCHAR(MAX))
PRINT 'ErrorMessage : ' + CAST(ERROR_MESSAGE() AS NVARCHAR(MAX))
PRINT '***********************************************************************************************************************************************************'
-- FINE Procedura in errore =========================================================================================================================================================
END
set @script=''
return -1
END CATCH
-- ##############################################################################################################################################################################
to exec it:
declare @s varchar(max)
exec [util_ScriptTable] 'db','schema_source','table_source',1,1,'schema_dest','tab_dest',0,@s output
select @s
If you have Gimp, I saw that exporting the image in .eps format would do the job.
It's a matter of operator precedence.
||
has a higher precedence than or
.
So, in between the two you have other operators including ternary (? :
) and assignment (=
) so which one you choose can affect the outcome of statements.
Here's a ruby operator precedence table.
See this question for another example using and
/&&
.
Also, be aware of some nasty things that could happen:
a = false || true #=> true
a #=> true
a = false or true #=> true
a #=> false
Both of the previous two statements evaluate to true
, but the second sets a
to false
since =
precedence is lower than ||
but higher than or
.
Found out for Samsung, Installing Kies also update the usb driver which solve my problem with connecting my Samsung Galaxy S Advance with Android 4.1.2 to Android Studio on Windows 7 64bit. In this case the devise manager shows device driver is updated and working, but when I connect my phone Android Studio does not recognize my device.
Actually I am preferring to use NEW_BROKER
,it is working fine on all cases:
ALTER DATABASE [dbname] SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
The reason to prefer Promises over callback functions is to have multiple callbacks and to avoid the problems like Callback Hell.
Callback hell (for more details, refer http://callbackhell.com/): Asynchronous javascript, or javascript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:
asyncCall(function(err, data1){
if(err) return callback(err);
anotherAsyncCall(function(err2, data2){
if(err2) return calllback(err2);
oneMoreAsyncCall(function(err3, data3){
if(err3) return callback(err3);
// are we done yet?
});
});
});
With Promises above code can be rewritten as below:
asyncCall()
.then(function(data1){
// do something...
return anotherAsyncCall();
})
.then(function(data2){
// do something...
return oneMoreAsyncCall();
})
.then(function(data3){
// the third and final async response
})
.fail(function(err) {
// handle any error resulting from any of the above calls
})
.done();
Contrary to what cularis said there can be both in the parameter map.
The best way I see is to proxy the parameterMap and for each parameter retrieval check if queryString contains "&?<parameterName>=".
Note that parameterName needs to be URL encoded before this check can be made, as Qerub pointed out.
That saves you the parsing and still gives you only URL parameters.
This worked for me:
private void AppName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem cbi = (ComboBoxItem)AppName.SelectedItem;
string selectedText = cbi.Content.ToString();
}
Project>>Clean and Maven>>Update Project worked for me
Use re.sub
directly, this allows you to specify a count
:
regex.sub('', url, 1)
(Note that the order of arguments is replacement
, original
not the opposite, as might be suspected.)
When publishing to IIS, by Web Deploy, I just checked the File Publish Options and executed. Now it works! After this deploy the checkboxes do not need to be checked. I don't think this can be a solutions for everybody, but it is the only thing I needed to do to solve my problem. Good luck.
the documentation has explained
- One difference is that interfaces create a new name that is used everywhere. Type aliases don’t create a new name — for instance, error messages won’t use the alias name.in older versions of TypeScript, type aliases couldn’t be extended or implemented from (nor could they extend/implement other types). As of version 2.7, type aliases can be extended by creating a new intersection type
- On the other hand, if you can’t express some shape with an interface and you need to use a union or tuple type, type aliases are usually the way to go.
The original syntax will work with BASH but not with DASH. On debian systems you might think you are using bash, but maybe dash instead. If /bin/dash/exist then try temporarily renaming dash to something like no.dash, and then create soft a link, aka ln -s /bin/bash /bin/dash and see if that fixes the problem.
Be sure to find out your current working directory, and write your filepath relative to it.
This code:
File here = new File(".");
System.out.println(here.getAbsolutePath());
... will print out that directory.
Also, unrelated to your question, try to use File.separator
to remain OS-independent. Backslashes work only on Windows.
Correct the ORACLE_HOME path.
There could be two oracle clients in the system.
I had the same issue, the reason being my ORACLE_HOME was pointed to the oracle installation which was not having the tns.ora file.
Changing the ORACLE_HOME to the Oracle directory which is having the tns.ora solved it.
tns.ora lies in client2\network\admin\
You can use the gcc compiler in linux to link two c file in one output. Suppose you have two c files one is 'main.c' and another is 'support.c'. So the command to link these two is
gcc main.c support.c -o main.out
By this two files will be linked to a single output main.out To run the output the command will be
./main.out
If you are using function in main.c which is declared in support.c file then you should declare it in main also using extern storage class.
I think these could be helpful for you .
Using a SELECT
statement with a simple CASE
expression
Within a SELECT
statement, a simple CASE
expression allows for only an equality check; no other comparisons are made. The following example uses the CASE
expression to change the display of product line categories to make them more understandable.
USE AdventureWorks2012;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
Using a SELECT
statement with a searched CASE
expression
Within a SELECT
statement, the searched CASE
expression allows for values to be replaced in the result set based on comparison values. The following example displays the list price as a text comment based on the price range for a product.
USE AdventureWorks2012;
GO
SELECT ProductNumber, Name, "Price Range" =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
Using CASE
in an ORDER BY
clause
The following examples uses the CASE
expression in an ORDER BY
clause to determine the sort order of the rows based on a given column value. In the first example, the value in the SalariedFlag column of the HumanResources.Employee table is evaluated. Employees that have the SalariedFlag set to 1 are returned in order by the BusinessEntityID in descending order. Employees that have the SalariedFlag set to 0 are returned in order by the BusinessEntityID in ascending order. In the second example, the result set is ordered by the column TerritoryName when the column CountryRegionName is equal to 'United States' and by CountryRegionName for all other rows.
SELECT BusinessEntityID, SalariedFlag
FROM HumanResources.Employee
ORDER BY CASE SalariedFlag WHEN 1 THEN BusinessEntityID END DESC
,CASE WHEN SalariedFlag = 0 THEN BusinessEntityID END;
GO
SELECT BusinessEntityID, LastName, TerritoryName, CountryRegionName
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL
ORDER BY CASE CountryRegionName WHEN 'United States' THEN TerritoryName
ELSE CountryRegionName END;
Using CASE
in an UPDATE
statement
The following example uses the CASE
expression in an UPDATE
statement to determine the value that is set for the column VacationHours for employees with SalariedFlag set to 0. When subtracting 10 hours from VacationHours results in a negative value, VacationHours is increased by 40 hours; otherwise, VacationHours is increased by 20 hours. The OUTPUT
clause is used to display the before and after vacation values.
USE AdventureWorks2012;
GO
UPDATE HumanResources.Employee
SET VacationHours =
( CASE
WHEN ((VacationHours - 10.00) < 0) THEN VacationHours + 40
ELSE (VacationHours + 20.00)
END
)
OUTPUT Deleted.BusinessEntityID, Deleted.VacationHours AS BeforeValue,
Inserted.VacationHours AS AfterValue
WHERE SalariedFlag = 0;
Using CASE
in a HAVING
clause
The following example uses the CASE
expression in a HAVING
clause to restrict the rows returned by the SELECT
statement. The statement returns the the maximum hourly rate for each job title in the HumanResources.Employee table. The HAVING
clause restricts the titles to those that are held by men with a maximum pay rate greater than 40 dollars or women with a maximum pay rate greater than 42 dollars.
USE AdventureWorks2012;
GO
SELECT JobTitle, MAX(ph1.Rate)AS MaximumRate
FROM HumanResources.Employee AS e
JOIN HumanResources.EmployeePayHistory AS ph1 ON e.BusinessEntityID = ph1.BusinessEntityID
GROUP BY JobTitle
HAVING (MAX(CASE WHEN Gender = 'M'
THEN ph1.Rate
ELSE NULL END) > 40.00
OR MAX(CASE WHEN Gender = 'F'
THEN ph1.Rate
ELSE NULL END) > 42.00)
ORDER BY MaximumRate DESC;
For more details description of these example visit the source.
Also visit here and here for some examples with great details.
Simply let it ignore the URI Exposure... Add it after on create
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build());
GitHub suggests that you should make sure to only use \n as a newline character in git-handled repos. There's an option to auto-convert:
$ git config --global core.autocrlf true
Of course, this is said to convert crlf to lf, while you want to convert cr to lf. I hope this still works …
And then convert your files:
# Remove everything from the index
$ git rm --cached -r .
# Re-add all the deleted files to the index
# You should get lots of messages like: "warning: CRLF will be replaced by LF in <file>."
$ git diff --cached --name-only -z | xargs -0 git add
# Commit
$ git commit -m "Fix CRLF"
core.autocrlf is described on the man page.
No need to increase the MaxConnections & InitialConnections. Just close your connections after after doing your work. For example if you are creating connection:
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1/"+dbname,user,pass);
} catch (SQLException e) {
e.printStackTrace();
return;
}
After doing your work close connection:
try {
connection.commit();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
process.env.NODE_ENV is adding a white space do this
process.env.NODE_ENV.trim() == 'production'
editTextObject.setText(CharSequence)
http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)
If anyone needs the JS code for calculating the trendline of many points on a graph, here's what worked for us in the end:
/**@typedef {{_x000D_
* x: Number;_x000D_
* y:Number;_x000D_
* }} Point_x000D_
* @param {Point[]} data_x000D_
* @returns {Function} */_x000D_
function _getTrendlineEq(data) {_x000D_
const xySum = data.reduce((acc, item) => {_x000D_
const xy = item.x * item.y_x000D_
acc += xy_x000D_
return acc_x000D_
}, 0)_x000D_
const xSum = data.reduce((acc, item) => {_x000D_
acc += item.x_x000D_
return acc_x000D_
}, 0)_x000D_
const ySum = data.reduce((acc, item) => {_x000D_
acc += item.y_x000D_
return acc_x000D_
}, 0)_x000D_
const aTop = (data.length * xySum) - (xSum * ySum)_x000D_
const xSquaredSum = data.reduce((acc, item) => {_x000D_
const xSquared = item.x * item.x_x000D_
acc += xSquared_x000D_
return acc_x000D_
}, 0)_x000D_
const aBottom = (data.length * xSquaredSum) - (xSum * xSum)_x000D_
const a = aTop / aBottom_x000D_
const bTop = ySum - (a * xSum)_x000D_
const b = bTop / data.length_x000D_
return function trendline(x) {_x000D_
return a * x + b_x000D_
}_x000D_
}
_x000D_
It takes an array of (x,y) points and returns the function of a y given a certain x Have fun :)
update for swift 5
let nextDate = fromDate.addingTimeInterval(60*60*24)
Use MySql Workbench's Export and Import functionality.
Steps:
1. Select the values you want
E.g. select * from table1;
create a new table using similar columns as the first one
E.g. create table table2 like table1;
select all from the new table
E.g. select * from table2;
Click on Import and select the CSV file you exported in step 2
In my case, I forgot (' or ") at the end of string. E.g 'ABC' or "ABC"
To simplify Amiram Korach's solution:
dtList.RemoveAll(s => string.IsNullOrWhiteSpace(s))
No need to use Distinct() or ToList()
The closest thing to "for each" is probably MySQL Procedure using Cursor and LOOP.
The formula
=OFFSET(Sheet1!$A$1,MOD(ROW()-1,COUNT(Sheet1!$A$1:$A$20000)),
(ROW()-1)/COUNT(Sheet1!$A$1:$A$20000))
placed into each cell of your second workbook will retrieve the appropriate cell from the source sheet. No macros, simple copying from one sheet to another to reformat the results.
You will need to modify the ranges in the COUNT function to match the maximum number of rows in the source sheet. Adjust for column headers as required.
If you need something other than a 0 for empty cells, you may prefer to include a conditional.
A script to reformat the data may well be more efficient, but 20k rows is no longer a real limit in a modern Excel workbook.
As long as you aren't using the NDK you can just ignore that warning.
By the way: This warning has nothing to do with parallel installations.
A key point that I find missing in the above answers is that urllib returns an object of type <class http.client.HTTPResponse>
whereas requests
returns <class 'requests.models.Response'>
.
Due to this, read() method can be used with urllib
but not with requests
.
P.S. : requests
is already rich with so many methods that it hardly needs one more as read()
;>
When a cookie is set with an explicit domain of 'localhost' as follows...
Set-Cookie: name=value; domain=localhost; expires=Thu, 16-Jul-2009 21:25:05 GMT; path=/
...then browsers ignore it because it does not include at least two periods and is not one of seven specially handled, top level domains.
...domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT".
Note that the number of periods above probably assumes that a leading period is required. This period is however ignored in modern browsers and it should probably read...
at least one (1) or two (2) periods
Note that the default value for the domain attribute is the host name of the server which generated the cookie response.
So a workaround for cookies not being set for localhost is to simply not specify a domain attribute and let the browser use the default value - this does not appear to have the same constraints that an explicit value in the domain attribute does.
The construct for this is:
<c:choose>
<c:when test="${..}">...</c:when> <!-- if condition -->
<c:when test="${..}">...</c:when> <!-- else if condition -->
<c:otherwise>...</c:otherwise> <!-- else condition -->
</c:choose>
If the condition isn't expensive, I sometimes prefer to simply use two distinct <c:if
tags - it makes it easier to read.
Let assume i am having a RestController
with GET/POST/PUT/DELETE
operations and i have to write unit test using spring boot.I will just share code of RestController class and respective unit test.Wont be sharing any other related code to the controller ,can have assumption on that.
@RestController
@RequestMapping(value = “/myapi/myApp” , produces = {"application/json"})
public class AppController {
@Autowired
private AppService service;
@GetMapping
public MyAppResponse<AppEntity> get() throws Exception {
MyAppResponse<AppEntity> response = new MyAppResponse<AppEntity>();
service.getApp().stream().forEach(x -> response.addData(x));
return response;
}
@PostMapping
public ResponseEntity<HttpStatus> create(@RequestBody AppRequest request) throws Exception {
//Validation code
service.createApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@PutMapping
public ResponseEntity<HttpStatus> update(@RequestBody IDMSRequest request) throws Exception {
//Validation code
service.updateApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@DeleteMapping
public ResponseEntity<HttpStatus> delete(@RequestBody AppRequest request) throws Exception {
//Validation
service.deleteApp(request.id);
return ResponseEntity.ok(HttpStatus.OK);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public abstract class BaseTest {
protected MockMvc mvc;
@Autowired
WebApplicationContext webApplicationContext;
protected void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
}
public class AppControllerTest extends BaseTest {
@MockBean
private IIdmsService service;
private static final String URI = "/myapi/myApp";
@Override
@Before
public void setUp() {
super.setUp();
}
@Test
public void testGet() throws Exception {
AppEntity entity = new AppEntity();
List<AppEntity> dataList = new ArrayList<AppEntity>();
AppResponse<AppEntity> dataResponse = new AppResponse<AppEntity>();
entity.setId(1);
entity.setCreated_at("2020-02-21 17:01:38.717863");
entity.setCreated_by(“Abhinav Kr”);
entity.setModified_at("2020-02-24 17:01:38.717863");
entity.setModified_by(“Jyoti”);
dataList.add(entity);
dataResponse.setData(dataList);
Mockito.when(service.getApp()).thenReturn(dataList);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI)
.accept(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String expectedJson = this.mapToJson(dataResponse);
String outputInJson = mvcResult.getResponse().getContentAsString();
assertEquals(HttpStatus.OK.value(), response.getStatus());
assertEquals(expectedJson, outputInJson);
}
@Test
public void testCreate() throws Exception {
AppRequest request = new AppRequest();
request.createdBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “India”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).createApp(Mockito.any(AppRequest.class));
service.createApp(request);
Mockito.verify(service, Mockito.times(1)).createApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testUpdate() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
request.modifiedBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “Bharat”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).updateApp(Mockito.any(AppRequest.class));
service.updateApp(request);
Mockito.verify(service, Mockito.times(1)).updateApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.put(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testDelete() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).deleteApp(Mockito.any(Integer.class));
service.deleteApp(request.id);
Mockito.verify(service, Mockito.times(1)).deleteApp(request.id);
RequestBuilder requestBuilder = MockMvcRequestBuilders.delete(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
}
This was added in the Chrome 56 beta, even though it isn't on this changelog from the Chromium Blog: Chrome 56 Beta: “Not Secure” warning, Web Bluetooth, and CSS position: sticky
You can hide this in the filter bar of the console with the Hide violations checkbox.
Simply edit my.ini
file in C:\xampp\mysql\bin path. Just add:
skip-grant-tables
line in between lines of # The MySQL server [mysqld]
and port=3306
. Then restart the MySQL server.
Looks like:
I found the following code easy and working. Original answer is here https://www.postgresql.org/message-id/[email protected]
prova=> create table test(t text, i integer);
CREATE
prova=> insert into test values('123',123);
INSERT 64579 1
prova=> select cast(i as text),cast(t as int)from test;
text|int4
----+----
123| 123
(1 row)
hope it helps
EDIT: From ECMAScript 2018 onwards, lookbehind assertions (even unbounded) are supported natively.
In previous versions, you can do this:
^(?:(?!filename\.js$).)*\.js$
This does explicitly what the lookbehind expression is doing implicitly: check each character of the string if the lookbehind expression plus the regex after it will not match, and only then allow that character to match.
^ # Start of string
(?: # Try to match the following:
(?! # First assert that we can't match the following:
filename\.js # filename.js
$ # and end-of-string
) # End of negative lookahead
. # Match any character
)* # Repeat as needed
\.js # Match .js
$ # End of string
Another edit:
It pains me to say (especially since this answer has been upvoted so much) that there is a far easier way to accomplish this goal. There is no need to check the lookahead at every character:
^(?!.*filename\.js$).*\.js$
works just as well:
^ # Start of string
(?! # Assert that we can't match the following:
.* # any string,
filename\.js # followed by filename.js
$ # and end-of-string
) # End of negative lookahead
.* # Match any string
\.js # Match .js
$ # End of string
If you're on Windows, they are installed with the platform SDK (or Visual Studio). However the header files are only compatible with OpenGL 1.1. You need to create function pointers for new functionality it later versions. Can you please clarify what version of OpenGL you're trying to use.
Here is my simple solution using Jquery filters.
$('#publisher').on('change', function(e) {
let selector = $(this).val();
$("#site > option").hide();
$("#site > option").filter(function(){return $(this).data('pub') == selector}).show();
});
Use:
YourActivityName.this
Instead of:
getApplicationContext();
Ok, i am shocked that no one really gave a good answer, now my turn. There are two cases;
A constant char array is good enough for you so you go with,
const char *array = tmp.c_str();
Or you need to modify the char array so constant is not ok, then just go with this
char *array = &tmp[0];
Both of them are just assignment operations and most of the time that is just what you need, if you really need a new copy then follow other fellows answers.
I'd just use zip
:
In [1]: from pandas import *
In [2]: def calculate(x):
...: return x*2, x*3
...:
In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})
In [4]: df
Out[4]:
a b
0 1 2
1 2 3
2 3 4
In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))
In [6]: df
Out[6]:
a b A1 A2
0 1 2 2 3
1 2 3 4 6
2 3 4 6 9
In my situation I needed to answer some questions without Y or N but with text or blank. I found the best way to do this in my situation was to create a shellscript file. In my case I called it autocomplete.sh
I was needing to answer some questions for a doctrine schema exporter so my file looked like this.
-- This is an example only --
php vendor/bin/mysql-workbench-schema-export mysqlworkbenchfile.mwb ./doctrine << EOF
`#Export to Doctrine Annotation Format` 1
`#Would you like to change the setup configuration before exporting` y
`#Log to console` y
`#Log file` testing.log
`#Filename [%entity%.%extension%]`
`#Indentation [4]`
`#Use tabs [no]`
`#Eol delimeter (win, unix) [win]`
`#Backup existing file [yes]`
`#Add generator info as comment [yes]`
`#Skip plural name checking [no]`
`#Use logged storage [no]`
`#Sort tables and views [yes]`
`#Export only table categorized []`
`#Enhance many to many detection [yes]`
`#Skip many to many tables [yes]`
`#Bundle namespace []`
`#Entity namespace []`
`#Repository namespace []`
`#Use automatic repository [yes]`
`#Skip column with relation [no]`
`#Related var name format [%name%%related%]`
`#Nullable attribute (auto, always) [auto]`
`#Generated value strategy (auto, identity, sequence, table, none) [auto]`
`#Default cascade (persist, remove, detach, merge, all, refresh, ) [no]`
`#Use annotation prefix [ORM\]`
`#Skip getter and setter [no]`
`#Generate entity serialization [yes]`
`#Generate extendable entity [no]` y
`#Quote identifier strategy (auto, always, none) [auto]`
`#Extends class []`
`#Property typehint [no]`
EOF
The thing I like about this strategy is you can comment what your answers are and using EOF a blank line is just that (the default answer). Turns out by the way this exporter tool has its own JSON counterpart for answering these questions, but I figured that out after I did this =).
to run the script simply be in the directory you want and run 'sh autocomplete.sh'
in terminal.
In short by using << EOL & EOF in combination with Return Lines you can answer each question of the prompt as necessary. Each new line is a new answer.
My example just shows how this can be done with comments also using the ` character so you remember what each step is.
Note the other advantage of this method is you can answer with more then just Y or N ... in fact you can answer with blanks!
Hope this helps someone out.
User interactive approach:
git clean -i -fd
Remove .classpath [y/N]? N
Remove .gitignore [y/N]? N
Remove .project [y/N]? N
Remove .settings/ [y/N]? N
Remove src/com/amazon/arsdumpgenerator/inspector/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/s3/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/s3/ [y/N]? y
-i for interactive
-f for force
-d for directory
-x for ignored files(add if required)
Note: Add -n or --dry-run to just check what it will do.
I'm not aware if you can create a migration from the command line to do all this, but you can create a new migration, then edit the migration to perform this taks.
If tablename is the name of your table, fieldname is the name of your field and you want to change from a datetime to date, you can write a migration to do this.
You can create a new migration with:
rails g migration change_data_type_for_fieldname
Then edit the migration to use change_table:
class ChangeDataTypeForFieldname < ActiveRecord::Migration
def self.up
change_table :tablename do |t|
t.change :fieldname, :date
end
end
def self.down
change_table :tablename do |t|
t.change :fieldname, :datetime
end
end
end
Then run the migration:
rake db:migrate
In Mac it is Alt+Command+L(assuming you haven't changed any of your modifier keys or Intellij keyboard shortcuts from it's default state)
This question can also be extended if necessary jar file can be found in global library, how can you configure it into your current project.
Process like these: "project structure"-->"modules"-->"click your current project pane at right"-->"dependencies"-->"click little add(+) button"-->"library"-->"select the library you want".
if you are using maven and you can also configure dependency in your pom.xml, but it your chosen version is not like the global library, you will waste memory on storing another version of the same jar file. so i suggest use the first step.
You can also try another library - https://github.com/wikimedia/jquery.i18n .
In addition to parameter replacement and multiple plural forms, it has support for gender a rather unique feature of custom grammar rules that some languages need.
You need to pass the labels to be dropped.
df.drop(df.index, inplace=True)
By default, it operates on axis=0
.
You can achieve the same with
df.iloc[0:0]
which is much more efficient.
No, according to Apple here:
Note: You cannot install apps from the App Store in simulation environments.
You are applying shapiro.test()
to a data.frame
instead of the column. Try the following:
shapiro.test(heisenberg$HWWIchg)
In java.lang.String
, the replace
method either takes a pair of char's or a pair of CharSequence
's (of which String is a subclass, so it'll happily take a pair of String's). The replace
method will replace all occurrences of a char or CharSequence
. On the other hand, the first String
arguments of replaceFirst
and replaceAll
are regular expressions (regex). Using the wrong function can lead to subtle bugs.
In Mac, Linux or Cygwin:
echo 'geo fix -99.133333 19.43333 2202' | nc localhost 5554
That will put you in Mexico City. Change your longitude/latitude/altitude accordingly. That should be enough if you are not interested in nmea.
Check this out! It was built no longer ago in 2014.
Get a list of country/state/city in a hierarchy using geonames webservice
You can run the following query
select sys_guid() from dual
union all
select sys_guid() from dual
union all
select sys_guid() from dual
Use this: https://github.com/gilamran/JQuery-Plugin-AnyChange
It handles all the ways to change the input, including content menu (Using the mouse)
Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu
.
This is the first description by the author taken from the github repository:
Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.
The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.
Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu
.
The following in an image of interface of the last version of pygubu
designer on a OS X Yosemite 10.10.2:
I would definitely give it a try, and contribute to its development.
i solved this in a shorter fashion.
Dim marray() as variant, array2() as variant, YY ,ZZ as integer
YY=1
ZZ=1
Redim marray(1 to 1000, 1 to 10)
Do while ZZ<100 ' this is populating the first array
marray(ZZ,YY)= "something"
ZZ=ZZ+1
YY=YY+1
Loop
'this part is where you store your array in another then resize and restore to original
array2= marray
Redim marray(1 to ZZ-1, 1 to YY)
marray = array2
Sometimes it is necessary to load scripts in a specific order. For example jQuery must be loaded before jQuery UI. Most examples on this page load scripts in parallel (asynchronously) which means order of execution is not guaranteed. Without ordering, script y
that depends on x
could break if both are successfully loaded but in wrong order.
I propose a hybrid approach which allows sequential loading of dependent scripts + optional parallel loading + deferred objects:
/*_x000D_
* loads scripts one-by-one using recursion_x000D_
* returns jQuery.Deferred_x000D_
*/_x000D_
function loadScripts(scripts) {_x000D_
var deferred = jQuery.Deferred();_x000D_
_x000D_
function loadScript(i) {_x000D_
if (i < scripts.length) {_x000D_
jQuery.ajax({_x000D_
url: scripts[i],_x000D_
dataType: "script",_x000D_
cache: true,_x000D_
success: function() {_x000D_
loadScript(i + 1);_x000D_
}_x000D_
});_x000D_
} else {_x000D_
deferred.resolve();_x000D_
}_x000D_
}_x000D_
loadScript(0);_x000D_
_x000D_
return deferred;_x000D_
}_x000D_
_x000D_
/*_x000D_
* example using serial and parallel download together_x000D_
*/_x000D_
_x000D_
// queue #1 - jquery ui and jquery ui i18n files_x000D_
var d1 = loadScripts([_x000D_
"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js",_x000D_
"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"_x000D_
]).done(function() {_x000D_
jQuery("#datepicker1").datepicker(jQuery.datepicker.regional.fr);_x000D_
});_x000D_
_x000D_
// queue #2 - jquery cycle2 plugin and tile effect plugin_x000D_
var d2 = loadScripts([_x000D_
"https://cdn.rawgit.com/malsup/cycle2/2.1.6/build/jquery.cycle2.min.js",_x000D_
"https://cdn.rawgit.com/malsup/cycle2/2.1.6/build/plugin/jquery.cycle2.tile.min.js"_x000D_
_x000D_
]).done(function() {_x000D_
jQuery("#slideshow1").cycle({_x000D_
fx: "tileBlind",_x000D_
log: false_x000D_
});_x000D_
});_x000D_
_x000D_
// trigger a callback when all queues are complete_x000D_
jQuery.when(d1, d2).done(function() {_x000D_
console.log("All scripts loaded");_x000D_
});
_x000D_
@import url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/blitzer/jquery-ui.min.css");_x000D_
_x000D_
#slideshow1 {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<p><input id="datepicker1"></p>_x000D_
_x000D_
<div id="slideshow1">_x000D_
<img src="https://dummyimage.com/300x100/FC0/000">_x000D_
<img src="https://dummyimage.com/300x100/0CF/000">_x000D_
<img src="https://dummyimage.com/300x100/CF0/000">_x000D_
</div>
_x000D_
The scripts in both queues will download in parallel, however, the scripts in each queue will download in sequence, ensuring ordered execution. Waterfall chart:
If you assign it to a class it should work:
<script>
function changeClass(){
document.getElementById('myButton').className = 'formatForButton';
}
</script>
<style>
.formatForButton {
background-color:pink;
}
</style>
<body>
<input id='myButton' type=button class=none value='Change Color to pink' onclick='changeClass()'>
</body>
*::after {
content: none !important;
}
*::before {
content: none !important;
}
_x000D_
Alternatively, you can use pseudo-elements to do so :) the advantage of the pseudo-element solution is that you can use it to space the inner border at an arbitrary distance away from the actual border, and the background will show through that space. The markup:
body {_x000D_
background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
background-repeat: no-repeat;_x000D_
height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
background-color: #ccc;_x000D_
border: 4px solid #fff;_x000D_
padding: 2em;_x000D_
width: 16em;_x000D_
height: 16em;_x000D_
position: relative;_x000D_
margin: 0 auto;_x000D_
}_x000D_
.double-border:before {_x000D_
background: none;_x000D_
border: 4px solid #fff;_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 4px;_x000D_
left: 4px;_x000D_
right: 4px;_x000D_
bottom: 4px;_x000D_
pointer-events: none;_x000D_
}
_x000D_
<div class="double-border">_x000D_
<!-- Content -->_x000D_
</div>
_x000D_
If you want borders that are consecutive to each other (no space between them), you can use multiple box-shadow
declarations (separated by commas) to do so:
body {_x000D_
background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
background-repeat: no-repeat;_x000D_
height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
background-color: #ccc;_x000D_
border: 4px solid #fff;_x000D_
box-shadow:_x000D_
inset 0 0 0 4px #eee,_x000D_
inset 0 0 0 8px #ddd,_x000D_
inset 0 0 0 12px #ccc,_x000D_
inset 0 0 0 16px #bbb,_x000D_
inset 0 0 0 20px #aaa,_x000D_
inset 0 0 0 20px #999,_x000D_
inset 0 0 0 20px #888;_x000D_
/* And so on and so forth, if you want border-ception */_x000D_
margin: 0 auto;_x000D_
padding: 3em;_x000D_
width: 16em;_x000D_
height: 16em;_x000D_
position: relative;_x000D_
}
_x000D_
<div class="double-border">_x000D_
<!-- Content -->_x000D_
</div>
_x000D_
First of all, you need to login as root and than go to /etc directory and execute some commands which are given below.
[root@localhost~]# cd /etc
[root@localhost /etc]# vi sudoers
and enter this line at the end
kundan ALL=NOPASSWD: ALL
where kundan is the username and than save it. and then try to transfer the file and add sudo
as a prefix to the command you want to execute:
sudo cp hello.txt /home/rahul/program/
where rahul is the second user in the same server.
In addition to the above answers, there is always the scorched earth method.
rm -R <folder>
in Windows shell the command is:
rd /s <folder>
Then you can just checkout the project again:
git clone -v <repository URL>
This will definitely remove any local changes and pull the latest from the remote repository. Be careful with rm -R as it will delete your good data if you put the wrong path. For instance, definitely do not do:
rm -R /
edit: To fix spelling and add emphasis.
You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.
If you don't use the onLocationChanged it always will be the old location.
How about this one: typically it is recommended that you do not expose a List object to external users of an assembly, rather expose an IEnumerable. But it is lot easier to use a List object inside the assembly, because you get the array syntax, and all other List methods. So, I typically have a internal property exposing a List to be used inside the assembly.
Comments are welcome about this approach.
you can use:
df.plot(x='Date',y='adj_close')
Or you can set the index to be Date
beforehand, then it's easy to plot the column you want:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
ticker
on itYou need to groupby before:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
Here is the correct implementation using numpy (np.log()
is the natural logarithm)
import numpy as np
p = 100
r = 0.06 / 12
FV = 4000
n = np.log(1 + FV * r/ p) / np.log(1 + r)
print ("Number of periods = " + str(n))
Output:
Number of periods = 36.55539635919235
select name, price
from (
select name, price,
row_number() over (order by price) r
from items
)
where r between 1 and 5;
The error shows that com.bd.service.ArticleService
is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:
<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>
Alternatively, if you want to include all subpackages in com.bd
:
<context:component-scan base-package="com.bd">
<context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>
As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan
annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration
.
@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {
@Autowired
ArticleService articleService;
...
}
You might find this Spring in depth section on Autowiring useful.
One thing that I have to add is that there is no reference in C.
Secondly, this is the language syntax convention. & - is an address operator but it also mean a reference - all depends on usa case
If there was some "reference" keyword instead of & you could write
int CDummy::isitme (reference CDummy param)
but this is C++ and we should accept it advantages and disadvantages...
There are many ways to do this if you want to write css then add following
.modal-dialog{
display: table
}
In case if you want to add inline
<div class="modal-dialog" style="display:table;">
//enter code here
</div>
Don't add display:table;
to modal-content class. it done your job but disposition your modal for large size see following screenshots.
first image is if you add style to modal-dialog
if you add style to modal-content. it looks dispositioned.
I got it to work like this:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
$(function () {
$('#uiEmailAdress').focus();
$('#NewsletterForm').validate({
rules: {
uiEmailAdress:{
required: true,
email: true,
minlength: 5
},
uiConfirmEmailAdress:{
required: true,
email: true,
equalTo: '#uiEmailAdress'
},
DDLanguage:{
required: true
},
Testveld:{
required: true,
regex: /^[0-9]{3}$/
}
},
messages: {
uiEmailAdress:{
required: 'Verplicht veld',
email: 'Ongeldig emailadres',
minlength: 'Minimum 5 charaters vereist'
},
uiConfirmEmailAdress:{
required: 'Verplicht veld',
email: 'Ongeldig emailadres',
equalTo: 'Veld is niet gelijk aan E-mailadres'
},
DDLanguage:{
required: 'Verplicht veld'
},
Testveld:{
required: 'Verplicht veld',
regex: '_REGEX'
}
}
});
});
Make sure that the regex is between /
:-)
I use docker stats $(docker ps --format={{.Names}}) --no-stream
to get :
Old answer (applicable till 2016)
Here's an Apple developer link that explicitly says that -
on iPhone and iPod touch, which are small screen devices, "Video is NOT presented within the Web Page"
Safari Device-Specific Considerations
Your options:
webkit-playsinline
attribute works for HTML5 videos on iOS but only when you save the webpage to your home screen as a webapp - Not if opened a page in SafariUIWebView
allows to play the video inline, but only if you set the allowsInlineMediaPlayback
property for the UIWebView
class to trueA tool is a big help.
However, there are times when you can't use a tool: the heap dump is so huge it crashes the tool, you are trying to troubleshoot a machine in some production environment to which you only have shell access, etc.
In that case, it helps to know your way around the hprof dump file.
Look for SITES BEGIN. This shows you what objects are using the most memory. But the objects aren't lumped together solely by type: each entry also includes a "trace" ID. You can then search for that "TRACE nnnn" to see the top few frames of the stack where the object was allocated. Often, once I see where the object is allocated, I find a bug and I'm done. Also, note that you can control how many frames are recorded in the stack with the options to -Xrunhprof.
If you check out the allocation site, and don't see anything wrong, you have to start backward chaining from some of those live objects to root objects, to find the unexpected reference chain. This is where a tool really helps, but you can do the same thing by hand (well, with grep). There is not just one root object (i.e., object not subject to garbage collection). Threads, classes, and stack frames act as root objects, and anything they reference strongly is not collectible.
To do the chaining, look in the HEAP DUMP section for entries with the bad trace id. This will take you to an OBJ or ARR entry, which shows a unique object identifier in hexadecimal. Search for all occurrences of that id to find who's got a strong reference to the object. Follow each of those paths backward as they branch until you figure out where the leak is. See why a tool is so handy?
Static members are a repeat offender for memory leaks. In fact, even without a tool, it'd be worth spending a few minutes looking through your code for static Map members. Can a map grow large? Does anything ever clean up its entries?
Remove your SSH keys from ~/.ssh
(or where you stored them).
Remove your user settings:
git config --global --unset user.name
git config --global --unset user.email
git config --global --unset credential.helper
Or all your global settings:
git config --global --unset-all
Maybe there's something else related to the credentials store, but I always used git over SSH.
From php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
This will work as well:
$array = explode('.', $_FILES['image']['name']);
$extension = end($array);
.html
- DOS has been dead for a long time. But it doesn't really make much difference in the end.
Dawid Ferenczy's answer is pretty complete but after I tried almost all of his options I've found that the Chocolatey’s cyg-get was the best (at least the only one that I could get to work).
I was wanting to install wget
, the steps was this:
choco install cyg-get
Then:
cyg-get wget
Function
Public Function ArrayLen(arr As Variant) As Integer
ArrayLen = UBound(arr) - LBound(arr) + 1
End Function
Usage
Dim arr(1 To 3) As String ' Array starting at 1 instead of 0: nightmare fuel
Debug.Print ArrayLen(arr) ' Prints 3. Everything's going to be ok.
array[index] == 'undefined'
compares the value of the array index to the string "undefined".
You're probably looking for typeof array[index] == 'undefined'
, which compares the type.
If you use IIS, Go to the Application pool Select the one that your site uses and click Advance Settings Make sure that the Enable 32-Bit Applications is set to True
Here is an example that sorts by the header. This table is dynamic and changes with the JSON size.
I was able to build a dynamic table off of some other people's examples and documentation. http://jsfiddle.net/lastlink/v7pszemn/1/
<tr>
<th class="{{header}}" ng-repeat="(header, value) in items[0]" ng-click="changeSorting(header)">
{{header}}
<i ng-class="selectedCls2(header)"></i>
</tr>
<tbody>
<tr ng-repeat="row in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
<td ng-repeat="cell in row">
{{cell}}
</td>
</tr>
Although the columns are out of order, on my .NET project they are in order.
try
pip3 install --user --upgrade pandas
And if you want to put it into string within some text context, forget about +
operator.
Simply do:
// Qt 5 + C++11
auto i = 13;
auto printable = QStringLiteral("My magic number is %1. That's all!").arg(i);
// Qt 5
int i = 13;
QString printable = QStringLiteral("My magic number is %1. That's all!").arg(i);
// Qt 4
int i = 13;
QString printable = QString::fromLatin1("My magic number is %1. That's all!").arg(i);
I was looking for this exact same thing and found that you can do:
strace -ewrite -p $PID
It's not exactly what you needed, but it's quite close.
I tried the redirecting output, but that didn't work for me. Maybe because the process was writing to a socket, I don't know.
Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.
The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.
There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.
Its name is Wifi Config Advanced Editor.
First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.
Save it.
Go to the WCE and edit the parameters of the network you have created in the previous step.
There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.
When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.
Do not Edit the network again with the Android wifi interface.
I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.
Use double quotes instead of single quote eg :
where('customer.name', 'LIKE', "%$findcustomer%")
Below is my code:
public function searchCustomer($findcustomer)
{
$customer = DB::table('customer')
->where('customer.name', 'LIKE', "%$findcustomer%")
->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
->get();
return View::make("your view here");
}
I clear my screen using is function that
var clear_body = function (){
var lista = document.body.childNodes;
for (var i = lista.length - 1; i >= 0 ;i--){
document.body.removeChild(lista[i])
}
}
yes we can do this using nth-child like so
div:nth-child(n + 8) {
background: red;
}
This will make the 8th div child onwards become red. Hope this helps...
Also, if someone ever says "hey, they can't be done with styled using css, use JS!!!" doubt them immediately. CSS is extremely flexible nowadays
Example :: http://jsfiddle.net/uWrLE/1/
In the example the first 7 children are blue, then 8 onwards are red...
What worked for me
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);
If you want to check or validate a specific UUID version, here are the corresponding regexes.
Note that the only difference is the version number, which is explained in
4.1.3. Version
chapter of UUID 4122 RFC.
The version number is the first character of the third group : [VERSION_NUMBER][0-9A-F]{3}
:
UUID v1 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v2 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v3 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v4 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v5 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
You could use the following:
mydiv.style.display === 'block' = (mydiv.style.display === 'block' ? 'none' : 'block');
Try wrapping the spans in an anchor tag and apply the background image to that.
HTML:
<div class="header">
<a href="/">
<span class="header-title">My gray sea design</span><br />
<span class="header-title-two">A beautiful design</span>
</a>
</div>
CSS:
.header {
border-bottom:1px solid #eaeaea;
}
.header a {
display: block;
background-image: url("./images/embouchure.jpg");
background-repeat: no-repeat;
height:160px;
padding-left:280px;
padding-top:50px;
width:470px;
color: #eaeaea;
}
With the v3 API, you can easily close the InfoWindow
with the InfoWindow.close()
method. You simply need to keep a reference to the InfoWindow
object that you are using. Consider the following example, which opens up an InfoWindow
and closes it after 5 seconds:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API InfoWindow Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 500px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(-25.36388, 131.04492),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
infowindow.open(map, marker);
setTimeout(function () { infowindow.close(); }, 5000);
</script>
</body>
</html>
If you have a separate InfoWindow
object for each Marker
, you may want to consider adding the InfoWindow
object as a property of your Marker
objects:
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
marker.infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
Then you would be able to open and close that InfoWindow
as follows:
marker.infowindow.open(map, marker);
marker.infowindow.close();
The same applies if you have an array of markers:
var markers = [];
marker[0] = new google.maps.Marker({
position: map.getCenter(),
map: map
});
marker[0].infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
// ...
marker[0].infowindow.open(map, marker);
marker[0].infowindow.close();
I found this solution:
$('.SeeMore2').click(function(){
var $this = $(this);
$this.toggleClass('SeeMore2');
if($this.hasClass('SeeMore2')){
$this.text('See More');
} else {
$this.text('See Less');
}
});
This should do it. You have to make sure you toggle the correct class and take out the "." from the hasClass