Try this. It worked fine for me
npm install /your_floder_location package_name --registry http://registry.npmjs.org/
Below is the exact command for me for installing vue-router package in my laravel project (my project name vue_laravel)
aslam004:vue_laravel $ npm install /var/www/html/projects/vue_laravel vue-router --registry http://registry.npmjs.org/
Good luck
List Of Key codes:
a - z-> 29 - 54
"0" - "9"-> 7 - 16
BACK BUTTON - 4, MENU BUTTON - 82
UP-19, DOWN-20, LEFT-21, RIGHT-22
SELECT (MIDDLE) BUTTON - 23
SPACE - 62, SHIFT - 59, ENTER - 66, BACKSPACE - 67
Create class with namespace name might resovle your issue
namespace.Employee employee = new namespace.Employee();
employee.ExampleMethod();
You can easily customize the android Navigation drawer once you know how its implemented. here is a nice tutorial where you can set it up.
This will be the structure of your mainXML:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>
You can customize this listview to your liking by adding the header. And radiobuttons.
Late to the party, MY two cents are given below after some research. During logout, make sure following things are happening...
Clear the client storage/session
Update the user table last login date-time and logout date-time whenever login or logout happens respectively. So login date time always should be greater than logout (Or keep logout date null if the current status is login and not yet logged out)
This is way far simple than keeping additional table of blacklist and purging regularly. Multiple device support requires additional table to keep loggedIn, logout dates with some additional details like OS-or client details.
You are using jQuery(document).ready(function($) {}
means here you are using jQuery
instead of $
. So to resolve your issue use following code.
jQuery("#submittername").text(submitter_name);
This will resolve your problem.
Since some of the functions depend on other libraries like GEOS and proj4 you might want to get their versions too. Then use:
SELECT PostGIS_full_version();
Environment
My OS is Ubuntu 16.04 and jupyter is 4.3.0.
Method
First, i logged out jupyter at its homepage on browser(the logout button is at top-right)
Second, type in Ctrl + C
in your terminal and it shows:
[I 15:59:48.407 NotebookApp]interrupted Serving notebooks from local directory: /home/Username 0 active kernels
The Jupyter Notebook is running at: http://localhost:8888/?token=a572c743dfb73eee28538f9a181bf4d9ad412b19fbb96c82
Shutdown this notebook server (y/[n])?
Last step, type in y
within 5 sec, and if it shows:
[C 15:59:50.407 NotebookApp] Shutdown confirmed
[I 15:59:50.408 NotebookApp] Shutting down kernels
Congrats! You close your jupyter successfully.
I think the problem is that you are using type="text" instead of textarea. What you want is:
<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>
To clarify, a type="text" will always be one row, where-as a textarea can be multiple.
Placing this date_default_timezone_set('Asia/Kolkata');
on config.php above base url also works
PHP List of Supported Time Zones
application/config/config.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
date_default_timezone_set('Asia/Kolkata');
Another way I have found use full is if you wish to set a time zone for each user
Create a MY_Controller.php
create a column in your user table you can name it timezone or any thing you want to. So that way when user selects his time zone it can can be set to his timezone when login.
application/core/MY_Controller.php
<?php
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->set_timezone();
}
public function set_timezone() {
if ($this->session->userdata('user_id')) {
$this->db->select('timezone');
$this->db->from($this->db->dbprefix . 'user');
$this->db->where('user_id', $this->session->userdata('user_id'));
$query = $this->db->get();
if ($query->num_rows() > 0) {
date_default_timezone_set($query->row()->timezone);
} else {
return false;
}
}
}
}
Also to get the list of time zones in php
$timezones = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
foreach ($timezones as $timezone)
{
echo $timezone;
echo "</br>";
}
If you love the command line, you can also do this using drush with the watchdog show command:
drush ws
More information about this command available here:
To use Thickness
you need to create/change your project .NET framework
platform version to 4.5. becaus this method available only in version 4.5. (Also you can just download PresentationFramework.dll and give referense to this dll, without create/change your .NET framework
version to 4.5.)
But if you want to do this simple, You can use this code:
MyControl.Margin = new Padding(int left, int top, int right, int bottom);
also
MyControl.Margin = new Padding(int all);
This is simple and no needs any changes to your project
alphabet = map(chr, range(97,123)+range(65,91)) + map(str,range(0,10))
def lookup(k, a=alphabet):
if type(k) == int:
return a[k]
elif type(k) == str:
return a.index(k)
def encode(i, a=alphabet):
'''Takes an integer and returns it in the given base with mappings for upper/lower case letters and numbers 0-9.'''
try:
i = int(i)
except Exception:
raise TypeError("Input must be an integer.")
def incode(i=i, p=1, a=a):
# Here to protect p.
if i <= 61:
return lookup(i)
else:
pval = pow(62,p)
nval = i/pval
remainder = i % pval
if nval <= 61:
return lookup(nval) + incode(i % pval)
else:
return incode(i, p+1)
return incode()
def decode(s, a=alphabet):
'''Takes a base 62 string in our alphabet and returns it in base10.'''
try:
s = str(s)
except Exception:
raise TypeError("Input must be a string.")
return sum([lookup(i) * pow(62,p) for p,i in enumerate(list(reversed(s)))])a
Here's my version for whomever needs it.
You can parse the geolocation through the addresses. Create an Array with jquery like this:
//follow this structure
var addressesArray = [
'Address Str.No, Postal Area/city'
]
//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
//it will place marker based on the addresses, which they will be translated as geolocations.
var aMarker= new google.maps.Marker({
position: latlng,
map: map
});
});
}
Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.
SELECT * FROM Accounts WHERE Username LIKE '%$query%'
but it's not suggested. use PDO
Let me present to you a glorious but terrifying hack:
import types
def _obj():
return lambda: None
def LET(bindings, body, env=None):
'''Introduce local bindings.
ex: LET(('a', 1,
'b', 2),
lambda o: [o.a, o.b])
gives: [1, 2]
Bindings down the chain can depend on
the ones above them through a lambda.
ex: LET(('a', 1,
'b', lambda o: o.a + 1),
lambda o: o.b)
gives: 2
'''
if len(bindings) == 0:
return body(env)
env = env or _obj()
k, v = bindings[:2]
if isinstance(v, types.FunctionType):
v = v(env)
setattr(env, k, v)
return LET(bindings[2:], body, env)
You can now use this LET
form as such:
map(lambda x: LET(('y', x + 1,
'z', x - 1),
lambda o: o.y * o.z),
[1, 2, 3])
which gives: [0, 3, 8]
You can also send multiple headers, data (JSON for example), and specify Call method (POST,GET) into a single CUrl call like this:
curl -X POST(Get or whatever) \
http://your_url.com/api/endpoint \
-H 'Content-Type: application/json' \
-H 'header-element1: header-data1' \
-H 'header-element2: header-data2' \
......more headers................
-d '{
"JsonExArray": [
{
"json_prop": "1",
},
{
"json_prop": "2",
}
]
}'
ES6 Style
Math.min(...[0, 6].map(v => new Date(95, v, 1).getTimezoneOffset() * -1));
You control the access rights for members and functions using Private/Protected/Public right? so assuming the idea of each and every one of those 3 levels is clear, then it should be clear that we are missing something...
The declaration of a member/function as protected for example is pretty generic. You are saying that this function is out of reach for everyone (except for an inherited child of course). But what about exceptions? every security system lets you have some type of 'white list" right?
So friend lets you have the flexibility of having rock solid object isolation, but allows for a "loophole" to be created for things that you feel are justified.
I guess people say it is not needed because there is always a design that will do without it. I think it is similar to the discussion of global variables: You should never use them, There is always a way to do without them... but in reality, you see cases where that ends up being the (almost) most elegant way... I think this is the same case with friends.
It doesn't really do any good, other than let you access a member variable without using a setting function
well that is not exactly the way to look at it. The idea is to control WHO can access what, having or not a setting function has little to do with it.
If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.
char *ptr = "Hello";
printf("%40s\n", ptr);
That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).
If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf
statements like the one above, or do it in a loop, changing the value of ptr
each time.
Think about what a pinch
event is: two fingers on an element, moving toward or away from each other.
Gesture events are, to my knowledge, a fairly new standard, so probably the safest way to go about this is to use touch events like so:
(ontouchstart
event)
if (e.touches.length === 2) {
scaling = true;
pinchStart(e);
}
(ontouchmove
event)
if (scaling) {
pinchMove(e);
}
(ontouchend
event)
if (scaling) {
pinchEnd(e);
scaling = false;
}
To get the distance between the two fingers, use the hypot
function:
var dist = Math.hypot(
e.touches[0].pageX - e.touches[1].pageX,
e.touches[0].pageY - e.touches[1].pageY);
Another way is:
boolean isEven = false;
if((a % 2) == 0)
{
isEven = true;
}
But easiest way is still:
boolean isEven = (a % 2) == 0;
Like @Steve Kuo said.
I too solved this issue in my own project by solving this particular line in my code. I added the following.
[DatabaseGenerated(DatabaseGeneratedOption.None)]
After realizing my mistake I then went and changed it to
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
This further ensures that the field named "Id" increments in value each time a new row is inserted in the database
Here's a simple recursive version:
import datetime
import math
def is_prime(n, div=2):
if div> int(math.sqrt(n)): return True
if n% div == 0:
return False
else:
div+=1
return is_prime(n,div)
now = datetime.datetime.now()
until = raw_input("How many prime numbers my lord desires??? ")
until = int(until)
primelist=[]
i=1;
while len(primelist)<until:
if is_prime(i):
primelist.insert(0,i)
i+=1
else: i+=1
print "++++++++++++++++++++"
print primelist
finish = datetime.datetime.now()
print "It took your computer", finish - now , "secs to calculate it"
Here's a version using a recursive function with memory!:
import datetime
import math
def is_prime(n, div=2):
global primelist
if div> int(math.sqrt(n)): return True
if div < primelist[0]:
div = primelist[0]
for x in primelist:
if x ==0 or x==1: continue
if n % x == 0:
return False
if n% div == 0:
return False
else:
div+=1
return is_prime(n,div)
now = datetime.datetime.now()
print 'time and date:',now
until = raw_input("How many prime numbers my lord desires??? ")
until = int(until)
primelist=[]
i=1;
while len(primelist)<until:
if is_prime(i):
primelist.insert(0,i)
i+=1
else: i+=1
print "Here you go!"
print primelist
finish = datetime.datetime.now()
print "It took your computer", finish - now , " to calculate it"
Hope it helps :)
Here's the important part from the man page:
As the list of files/directories to transfer is built, rsync checks each name to be transferred against the list of include/exclude patterns in turn, and the first matching pattern is acted on: if it is an exclude pattern, then that file is skipped; if it is an include pattern then that filename is not skipped; if no matching pattern is found, then the filename is not skipped.
To summarize:
Also, something ending with a slash is matching directories (like find -type d
would).
Let's pull apart this answer from above.
rsync -zarv --prune-empty-dirs --include "*/" --include="*.sh" --exclude="*" "$from" "$to"
.sh
filesFinally, the --prune-empty-directories
keeps the first rule from making empty directories all over the place.
As other noted you have several options. If you want only mathematical functions. You can import only Darwin.
import Darwin
If you want mathematical functions and other standard classes and functions. You can import Foundation.
import Foundation
If you want everything and also classes for user interface, it depends if your playground is for OS X or iOS.
For OS X, you need import Cocoa.
import Cocoa
For iOS, you need import UIKit.
import UIKit
You can easily discover your playground platform by opening File Inspector (??1).
Python does not have a trailing if
statement.
There are two kinds of if
in Python:
if
statement:
if condition: statement
if condition:
block
if
expression (introduced in Python 2.5)
expression_if_true if condition else expression_if_false
And note, that both print a
and b = a
are statements. Only the a
part is an expression. So if you write
print a if b else 0
it means
print (a if b else 0)
and similarly when you write
x = a if b else 0
it means
x = (a if b else 0)
Now what would it print/assign if there was no else
clause? The print/assignment is still there.
And note, that if you don't want it to be there, you can always write the regular if
statement on a single line, though it's less readable and there is really no reason to avoid the two-line variant.
I know this thread is ancient, but after assigning the innerHTML, ExecWB worked for me:
.ExecWB 17, 0_x000D_
'Select all contents in browser_x000D_
.ExecWB 12, 2_x000D_
'Copy them
_x000D_
And then just paste the contents into Excel. Since these methods are prone to runtime errors, but work fine after one or two tries in debug mode, you might have to tell Excel to try again if it runs into an error. I solved this by adding this error handler to the sub, and it works fine:
Sub ApplyHTML()_x000D_
On Error GoTo ErrorHandler_x000D_
..._x000D_
Exit Sub_x000D_
_x000D_
ErrorHandler:_x000D_
Resume _x000D_
'I.e. re-run the line of code that caused the error_x000D_
Exit Sub_x000D_
_x000D_
End Sub
_x000D_
A really infinite loop, counting from 1 to 10 with increment of 0.
You need infinite or more increments to reach the 10.
for /L %%n in (1,0,10) do (
echo do stuff
rem ** can't be leaved with a goto (hangs)
rem ** can't be stopped with exit /b (hangs)
rem ** can be stopped with exit
rem ** can be stopped with a syntax error
call :stop
)
:stop
call :__stop 2>nul
:__stop
() creates a syntax error, quits the batch
This could be useful if you need a really infinite loop, as it is much faster than a goto :loop
version because a for-loop is cached completely once at startup.
I was not satisfied with swagger-codegen
when I was looking for a tool to do this, so I wrote my own. Have a look at bootprint-swagger
The main goal compared to swagger-codegen
is to provide an easy setup (though you'll need nodejs).
And it should be easy to adapt styling and templates to your own needs, which is a core functionality of the bootprint-project
For what it's worth, there is Jackson Hibernate module project that just started, and which should solve this problem and hopefully others as well. Project is related to Jackson project, although not part of core source. This is mostly to allow simpler release process; it will require Jackson 1.7 as that's when Module API is being introduced.
Here is a good example on how to do a command if a file does or does not exist:
if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit
We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.
xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"
Use the XCOPY command:
xcopy "C:\myprogram\html\data.sql" /c /d /h /e /i /y "C:\myprogram\sync\"
I will explain what the /c /d /h /e /i /y
means:
/C Continues copying even if errors occur.
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
/H Copies hidden and system files also.
/E Copies directories and subdirectories, including empty ones.
Same as /S /E. May be used to modify /T.
/T Creates directory structure, but does not copy files. Does not
include empty directories or subdirectories. /T /E includes
/I If destination does not exist and copying more than one file,
assumes that destination must be a directory.
/Y Suppresses prompting to confirm you want to overwrite an
existing destination file.
`To see all the commands type`xcopy /? in cmd
Call other batch file with option sync.bat myprogram.ini.
I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like
Path/sync.bat
Path/myprogram.ini
If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.
You are using a batch file. You mentioned earlier you have to create a .bat file to use this:
I have to create a .BAT file that does this:
In my case, it was an infinite sort. That is, at first the line moved up according to the condition, and then the same line moved down to the same place. I added one more condition at the end that unambiguously established the order of the lines.
Using the javascript engine that is shipped with Java 6:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Wow
{
public static void main(String[] args) throws Exception
{
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.eval("print(encodeURIComponent('\"A\" B ± \"'))");
}
}
Output: %22A%22%20B%20%c2%b1%20%22
The case is different but it's closer to what you want.
if you're wanting to chomp part of a filename from the path, "dirname" and "basename" are your friends, and "realpath" is handy too.
dirname /foo/bar/baz
# /foo/bar
basename /foo/bar/baz
# baz
dirname $( dirname /foo/bar/baz )
# /foo
realpath ../foo
# ../foo: No such file or directory
realpath /tmp/../tmp/../tmp
# /tmp
realpath
alternatives
If realpath
is not supported by your shell, you can try
readlink -f /path/here/..
Also
readlink -m /path/there/../../
Works the same as
realpath -s /path/here/../../
in that the path doesn't need to exist to be normalized.
If the variable is a parameter then you could use advanced function parameter binding like below to validate not null or empty:
[CmdletBinding()]
Param (
[parameter(mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Version
)
public static string ConvertToCaptilize(string input)
{
if (!string.IsNullOrEmpty(input))
{
string[] arrUserInput = input.Split(' ');
// Initialize a string builder object for the output
StringBuilder sbOutPut = new StringBuilder();
// Loop thru each character in the string array
foreach (string str in arrUserInput)
{
if (!string.IsNullOrEmpty(str))
{
var charArray = str.ToCharArray();
int k = 0;
foreach (var cr in charArray)
{
char c;
c = k == 0 ? char.ToUpper(cr) : char.ToLower(cr);
sbOutPut.Append(c);
k++;
}
}
sbOutPut.Append(" ");
}
return sbOutPut.ToString();
}
return string.Empty;
}
In 2021 the easiest way is to use asyncio:
import asyncio, time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(
say_after(4, 'hello'))
task2 = asyncio.create_task(
say_after(3, 'world'))
print(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
References:
I wrote a dump function, which basicly prints out the public members of an object if it has not overriden toString(). One could easily expand it to call getters. Javadoc:
Dumps an given Object to System.out, using the following rules:
- If the Object is Iterable, all of its components are dumped.
- If the Object or one of its superclasses overrides toString(), the "toString" is dumped
- Else the method is called recursively for all public members of the Object
/**
* Dumps an given Object to System.out, using the following rules:<br>
* <ul>
* <li> If the Object is {@link Iterable}, all of its components are dumped.</li>
* <li> If the Object or one of its superclasses overrides {@link #toString()}, the "toString" is dumped</li>
* <li> Else the method is called recursively for all public members of the Object </li>
* </ul>
* @param input
* @throws Exception
*/
public static void dump(Object input) throws Exception{
dump(input, 0);
}
private static void dump(Object input, int depth) throws Exception{
if(input==null){
System.out.print("null\n"+indent(depth));
return;
}
Class<? extends Object> clazz = input.getClass();
System.out.print(clazz.getSimpleName()+" ");
if(input instanceof Iterable<?>){
for(Object o: ((Iterable<?>)input)){
System.out.print("\n"+indent(depth+1));
dump(o, depth+1);
}
}else if(clazz.getMethod("toString").getDeclaringClass().equals(Object.class)){
Field[] fields = clazz.getFields();
if(fields.length == 0){
System.out.print(input+"\n"+indent(depth));
}
System.out.print("\n"+indent(depth+1));
for(Field field: fields){
Object o = field.get(input);
String s = "|- "+field.getName()+": ";
System.out.print(s);
dump(o, depth+1);
}
}else{
System.out.print(input+"\n"+indent(depth));
}
}
private static String indent(int depth) {
StringBuilder sb = new StringBuilder();
for(int i=0; i<depth; i++)
sb.append(" ");
return sb.toString();
}
Just pass var2 as an extra argument to one of the apply functions.
mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
var1*var2
}
var2 <- 2
sapply(mylist,myfxn,var2=var2)
This passes the same var2
to every call of myfxn
. If instead you want each call of myfxn
to get the 1st/2nd/3rd/etc. element of both mylist
and var2
, then you're in mapply
's domain.
In postman's collection runner you can't make simultaneous asynchronous requests, so instead use Apache JMeter instead. It allows you to add multiple threads and add synchronizing timer to it
The real answer has to include keyCode:
var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
e.keyCode = 50
$("input").trigger(e);
Even though jQuery's website says that which and keyCode are normalized they are very badly mistaken. It's always safest to do the standard cross-browser checks for e.which and e.keyCode and in this case just define both.
In C# 7 it's possible to use a when clause in a case statement.
int age = 12;
switch (age)
{
case int i when i >=1 && i <= 8:
System.Console.WriteLine("You are only " + age + " years old. You must be kidding right. Please fill in your *real* age.");
break;
case int i when i >=9 && i <= 15:
System.Console.WriteLine("You are only " + age + " years old. That's too young!");
break;
case int i when i >=16 && i <= 100:
System.Console.WriteLine("You are " + age + " years old. Perfect.");
break;
default:
System.Console.WriteLine("You an old person.");
break;
}
While debugging System.Diagnostics.Debug.WriteLine
will display in the output window (Ctrl+Alt+O), you can also add a TraceListener
to the Debug.Listeners
collection to specify Debug.WriteLine
calls to output in other locations.
Note: Debug.WriteLine
calls may not display in the output window if you have the Visual Studio option "Redirect all Output Window text to the Immediate Window" checked under the menu Tools ? Options ? Debugging ? General. To display "Tools ? Options ? Debugging", check the box next to "Tools ? Options ? Show All Settings".
To check that the file you're trying to open actually exists, you can change directories in terminal using cd
. To change to ~/Desktop/sass/css
: cd ~/Desktop/sass/css
. To see what files are in the directory: ls
.
If you want information about either of those commands, use the man
page: man cd
or man ls
, for example.
Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.
On Mac OS X, you can also use open
to open a finder window: open .
will open the current directory in finder. (open ~/Desktop/sass/css
will open the ~/Desktop/sass/css
).
What you have is a parse error. Those are thrown before any code is executed. A PHP file needs to be parsed in its entirety before any code in it can be executed. If there's a parse error in the file where you're setting your error levels, they won't have taken effect by the time the error is thrown.
Either break your files up into smaller parts, like setting the error levels in one file and then include
ing another file which contains the actual code (and errors), or set the error levels outside PHP using php.ini or .htaccess directives.
You have to give the dictionary a type
// empty dict with Ints as keys and Strings as values
var namesOfIntegers = Dictionary<Int, String>()
If the compiler can infer the type, you can use the shorter syntax
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type Int, String
$('#div_id').css({marginTop: '-=15px'});
This will alter the css for the element with the id "div_id"
To get the effect you want I recommend adding the code above to a callback function in your animation (that way the div will be moved up after the animation is complete):
$('#div_id').animate({...}, function () {
$('#div_id').css({marginTop: '-=15px'});
});
And of course you could animate the change in margin like so:
$('#div_id').animate({marginTop: '-=15px'});
Here are the docs for .css()
in jQuery: http://api.jquery.com/css/
And here are the docs for .animate()
in jQuery: http://api.jquery.com/animate/
You can do this using Cygwin’s setup.exe from Windows command line. Example:
cd C:\cygwin64
setup-x86_64 -q -P wget,tar,gawk,bzip2,subversion,vim
For a more convenient installer, you may want to use the apt-cyg package manager. Its syntax is similar to apt-get, which is a plus. For this, follow the above steps and then use Cygwin Bash for the following steps:
wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg
install apt-cyg /bin
Now that apt-cyg
is installed. Here are a few examples of installing some
packages:
apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates
The C way:
char buf[100];
strcpy(buf, one);
strcat(buf, two);
The C++ way:
std::string buf(one);
buf.append(two);
The compile-time way:
#define one "hello "
#define two "world"
#define concat(first, second) first second
const char* buf = concat(one, two);
This will do:
db.getCollectionNames().forEach(c => {
db[c].find().forEach(d => {
print(c);
printjson(d)
})
})
You can use monitorEvents function.
Just inspect your element (right mouse click
? Inspect
on visible element or go to Elements
tab in Chrome Developer Tools and select wanted element) then go to Console
tab and write:
monitorEvents($0)
Now when you move mouse over this element, focus or click it, the name of the fired event will be displayed with its data.
To stop getting this data just write this to console:
unmonitorEvents($0)
$0
is just the last DOM element selected by Chrome Developer Tools. You can pass any other DOM object there (for example result of getElementById
or querySelector
).
You can also specify event "type" as second parameter to narrow monitored events to some predefined set. For example:
monitorEvents(document.body, 'mouse')
List of this available types is here.
I made a small gif that illustrates how this feature works:
I thought this would help some when dealing with time zones too. My modified solution is based off of @Tim Cooper's solution, the correct answer above.
$minutes_to_add = 10;
$time = new DateTime();
**$time->setTimezone(new DateTimeZone('America/Toronto'));**
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$timestamp = $time->format("Y/m/d G:i:s");
The bold line, line 3, is the addition. I hope this helps some folks as well.
//@parram $data-array,$d-if true then die by default it is false
//@author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
} // END OF FUNCTION
Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function
In your case you can use in this way....
while($row = mysql_fetch_array($result)){
p($row); // Use this function if you use above function in your page.
}
When you say adding antMatchers doesnt help - what do you mean? antMatchers is exactly how you do it. Something like the following should work (obviously changing your URL appropriately):
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/authFailure").permitAll()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
If you are still not having any joy, then you will need to provide more details/stacktrace etc.
background-image
and use text-indent
or a padding
to shift the text to the right.Honestly, I would avoid usage of HTML5/CSS3 without a good fallback. There are just too many people using old browsers that don't support all the new fancy stuff. It will take a while before we can drop the fallback, unfortunately :(
The first method I mentioned is the safest and easiest. Both ways requires Javascript to hide the icon.
CSS:
input#search {
background-image: url(bg.jpg);
background-repeat: no-repeat;
text-indent: 20px;
}
HTML:
<input type="text" id="search" name="search" onchange="hideIcon(this);" value="search" />
Javascript:
function hideIcon(self) {
self.style.backgroundImage = 'none';
}
I can't believe I said "Both ways requires JavaScript to hide the icon.", because this is not entirely true.
The most common timing to hide placeholder text is on change, as suggested in this answer. For icons however it's okay to hide them on focus which can be done in CSS with the active
pseudo-class.
#search:active { background-image: none; }
Heck, using CSS3 you can make it fade away!
Of course, there's the CSS3 ::before pseudo-elements too. Beware of browser support though!
Chrome Firefox IE Opera Safari
:before (yes) 1.0 8.0 4 4.0
::before (yes) 1.5 9.0 7 4.0
CSS3 has the overflow-x
property, but I wouldn't expect great support for that. In CSS2 all you can do is set a general scroll
policy and work your widths
and heights
not to mess them up.
new
is the new goto
.
Recall why goto
is so reviled: while it is a powerful, low-level tool for flow control, people often used it in unnecessarily complicated ways that made code difficult to follow. Furthermore, the most useful and easiest to read patterns were encoded in structured programming statements (e.g. for
or while
); the ultimate effect is that the code where goto
is the appropriate way to is rather rare, if you are tempted to write goto
, you're probably doing things badly (unless you really know what you're doing).
new
is similar — it is often used to make things unnecessarily complicated and harder to read, and the most useful usage patterns can be encoded have been encoded into various classes. Furthermore, if you need to use any new usage patterns for which there aren't already standard classes, you can write your own classes that encode them!
I would even argue that new
is worse than goto
, due to the need to pair new
and delete
statements.
Like goto
, if you ever think you need to use new
, you are probably doing things badly — especially if you are doing so outside of the implementation of a class whose purpose in life is to encapsulate whatever dynamic allocations you need to do.
Firstly uninstall the existing npm package: npm uninstall -g create-react-app (-g if you installed globally) Secondly: npm cache clean --force Thirdly: npm install -g create-react-app@latest and create-react-app my-app again.
You can pass parameters with arbitrary attributes. This works in all recent browsers.
<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>
Inside somefile.js you can get passed variables values this way:
........
var this_js_script = $('script[src*=somefile]'); // or better regexp to get the file name..
var my_var_1 = this_js_script.attr('data-my_var_1');
if (typeof my_var_1 === "undefined" ) {
var my_var_1 = 'some_default_value';
}
alert(my_var_1); // to view the variable value
var my_var_2 = this_js_script.attr('data-my_var_2');
if (typeof my_var_2 === "undefined" ) {
var my_var_2 = 'some_default_value';
}
alert(my_var_2); // to view the variable value
...etc...
While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --
try:
line = raw_input()
... whatever needs to be done incase of no EOF ...
except EOFError:
... whatever needs to be done incase of EOF ...
Example:
$ echo test | python -c "while True: print raw_input()"
test
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
Or press Ctrl-Z at a raw_input()
prompt (Windows, Ctrl-Z Linux)
You can look at Open Source QR Code Library or messagingtoolkit-qrcode. I have not used either of them so I can not speak of their ease to use.
This should work:
// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);
If you want to convert dip to pixels, use this:
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());
as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.
awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:
variable=$(ps -ef | awk '/port 10 \-/ {print $12}')
variable=`ps -ef | awk '/port 10 \-/ {print $12}'`
The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.
This answer support the @ macrocosme suggestion.
I am using heat map as hist2d plot. Additionally I use cmin=0.5 for no count value and cmap for color, r represent the reverse of given color.
# np.arange(data.min(), data.max()+binwidth, binwidth)
bin_x = np.arange(0.6, 7 + 0.3, 0.3)
bin_y = np.arange(12, 58 + 3, 3)
plt.hist2d(data=fuel_econ, x='displ', y='comb', cmin=0.5, cmap='viridis_r', bins=[bin_x, bin_y]);
plt.xlabel('Dispalcement (1)');
plt.ylabel('Combine fuel efficiency (mpg)');
plt.colorbar();
The current spec says this regarding flex: 1 1 auto
:
Sizes the item based on the
width
/height
properties, but makes them fully flexible, so that they absorb any free space along the main axis. If all items are eitherflex: auto
,flex: initial
, orflex: none
, any positive free space after the items have been sized will be distributed evenly to the items withflex: auto
.
http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#flex-common
It sounds to me like if you say an element is 100px tall, it is treated more like a "suggested" size, not an absolute. Because it is allowed to shrink and grow, it takes up as much space as its allowed to. That's why adding this line to your "main" element works: height: 0
(or any other smallish number).
To add a header just add the following code to the location block where you want to add the header:
location some-location {
add_header X-my-header my-header-content;
}
Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.
Assuming that pwd
is just an example, this is how you can do it:
import subprocess
p = subprocess.Popen("pwd", stdout=subprocess.PIPE)
result = p.communicate()[0]
print result
See the subprocess documentation for another example and more information.
I wanted a more enhanced version so I ended up with a module which allows: UAC request if needed, printing and logging from nonprivileged instance (uses ipc and a network port) and some other candies. usage is just insert elevateme() in your script: in nonprivileged it listen for privileged print/logs and then exits returning false, in privileged instance it returns true immediately. Supports pyinstaller.
prototype:
# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
winadmin.py
#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4
# (C) COPYRIGHT © Preston Landers 2010
# (C) COPYRIGHT © Matteo Azzali 2020
# Released under the same license as Python 2.6.5/3.7
import sys, os
from traceback import print_exc
from multiprocessing.connection import Listener, Client
import win32event #win32com.shell.shell, win32process
import builtins as __builtin__ # python3
# debug suffixes for remote printing
dbz=["","","",""] #["J:","K:", "G:", "D:"]
LOGTAG="LOGME:"
wrconn = None
#fake logger for message sending
class fakelogger:
def __init__(self, xlogger=None):
self.lg = xlogger
def write(self, a):
global wrconn
if wrconn is not None:
wrconn.send(LOGTAG+a)
elif self.lg is not None:
self.lg.write(a)
else:
print(LOGTAG+a)
class Writer():
wzconn=None
counter = 0
def __init__(self, tport=6000,authkey=b'secret password'):
global wrconn
if wrconn is None:
address = ('localhost', tport)
try:
wrconn = Client(address, authkey=authkey)
except:
wrconn = None
wzconn = wrconn
self.wrconn = wrconn
self.__class__.counter+=1
def __del__(self):
self.__class__.counter-=1
if self.__class__.counter == 0 and wrconn is not None:
import time
time.sleep(0.1) # slows deletion but is enough to print stderr
wrconn.send('close')
wrconn.close()
def sendx(cls, mesg):
cls.wzconn.send(msg)
def sendw(self, mesg):
self.wrconn.send(msg)
#fake file to be passed as stdout and stderr
class connFile():
def __init__(self, thekind="out", tport=6000):
self.cnt = 0
self.old=""
self.vg=Writer(tport)
if thekind == "out":
self.kind=sys.__stdout__
else:
self.kind=sys.__stderr__
def write(self, *args, **kwargs):
global wrconn
global dbz
from io import StringIO # # Python2 use: from cStringIO import StringIO
mystdout = StringIO()
self.cnt+=1
__builtin__.print(*args, **kwargs, file=mystdout, end = '')
#handles "\n" wherever it is, however usually is or string or \n
if "\n" not in mystdout.getvalue():
if mystdout.getvalue() != "\n":
#__builtin__.print("A:",mystdout.getvalue(), file=self.kind, end='')
self.old += mystdout.getvalue()
else:
#__builtin__.print("B:",mystdout.getvalue(), file=self.kind, end='')
if wrconn is not None:
wrconn.send(dbz[1]+self.old)
else:
__builtin__.print(dbz[2]+self.old+ mystdout.getvalue(), file=self.kind, end='')
self.kind.flush()
self.old=""
else:
vv = mystdout.getvalue().split("\n")
#__builtin__.print("V:",vv, file=self.kind, end='')
for el in vv[:-1]:
if wrconn is not None:
wrconn.send(dbz[0]+self.old+el)
self.old = ""
else:
__builtin__.print(dbz[3]+self.old+ el+"\n", file=self.kind, end='')
self.kind.flush()
self.old=""
self.old=vv[-1]
def open(self):
pass
def close(self):
pass
def flush(self):
pass
def isUserAdmin():
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print ("Admin check failed, assuming not an admin.")
return False
elif os.name == 'posix':
# Check for root on Posix
return os.getuid() == 0
else:
print("Unsupported operating system for this module: %s" % (os.name,))
exit()
#raise (RuntimeError, "Unsupported operating system for this module: %s" % (os.name,))
def runAsAdmin(cmdLine=None, wait=True, hidden=False):
if os.name != 'nt':
raise (RuntimeError, "This function is only implemented on Windows.")
import win32api, win32con, win32process
from win32com.shell.shell import ShellExecuteEx
python_exe = sys.executable
arb=""
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif not isinstance(cmdLine, (tuple, list)):
if isinstance(cmdLine, (str)):
arb=cmdLine
cmdLine = [python_exe] + sys.argv
print("original user", arb)
else:
raise( ValueError, "cmdLine is not a sequence.")
cmd = '"%s"' % (cmdLine[0],)
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
if len(arb) > 0:
params += " "+arb
cmdDir = ''
if hidden:
showCmd = win32con.SW_HIDE
else:
showCmd = win32con.SW_SHOWNORMAL
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=64,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
#print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = procInfo['hProcess']
return rc
# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
global dbz
if not isUserAdmin():
print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
import getpass
uname = getpass.getuser()
if (tport> 0):
address = ('localhost', tport) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey=b'secret password')
rc = runAsAdmin(uname, wait=False, hidden=True)
if (tport> 0):
hr = win32event.WaitForSingleObject(rc, 40)
conn = listener.accept()
print ('connection accepted from', listener.last_accepted)
sys.stdout.flush()
while True:
msg = conn.recv()
# do something with msg
if msg == 'close':
conn.close()
break
else:
if msg.startswith(dbz[0]+LOGTAG):
if xlogger != None:
xlogger.write(msg[len(LOGTAG):])
else:
print("Missing a logger")
else:
print(msg)
sys.stdout.flush()
listener.close()
else: #no port connection, its silent
WaitForSingleObject(rc, INFINITE);
return False
else:
#redirect prints stdout on master, errors in error.txt
print("HIADM")
sys.stdout.flush()
if (tport > 0) and (redir):
vox= connFile(tport=tport)
sys.stdout=vox
if not errFile:
sys.stderr=vox
else:
vfrs=open("errFile.txt","w")
sys.stderr=vfrs
#print("HI ADMIN")
return True
def test():
rc = 0
if not isUserAdmin():
print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
sys.stdout.flush()
#rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
rc = runAsAdmin()
else:
print ("You are an admin!", os.getpid(), "params: ", sys.argv)
rc = 0
x = raw_input('Press Enter to exit.')
return rc
if __name__ == "__main__":
sys.exit(test())
Or if you want all PS1 files to work the way VBS files do, you can edit the registry like this:
HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command
Edit the Default value to be something like so...
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"
Then you can just double click all your .PS1 files like you would like to. in my humble opinion, be able to out of the box.
I'm going to call this "The Powershell De-castration Hack". LOL enjoy!
As the user running the Oracle Database one can also try $ORACLE_HOME/OPatch/opatch lsinventory
which shows the exact version and patches installed.
For example this is a quick oneliner which should only return the version number:
$ORACLE_HOME/OPatch/opatch lsinventory | awk '/^Oracle Database/ {print $NF}'
I usually use information_Schema.columns
and information_schema.tables
, although like @yuck said, sys.tables
and sys.columns
are shorter to type.
In a loop, concatenate these
@sql = @sql + 'select' + column_name +
' from ' + table_name +
' where ' + column_name ' like ''%''+value+''%' UNION
Then execute the resulting sql.
You simply want the File.GetLastWriteTime
static method.
Example:
var lastModified = System.IO.File.GetLastWriteTime("C:\foo.bar");
Console.WriteLine(lastModified.ToString("dd/MM/yy HH:mm:ss"));
Note however that in the rare case the last-modified time is not updated by the system when writing to the file (this can happen intentionally as an optimisation for high-frequency writing, e.g. logging, or as a bug), then this approach will fail, and you will instead need to subscribe to file write notifications from the system, constantly listening.
As per my understanding you want data in dictionary as shown below:
key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3
for this you can use list for each dictionary keys:
case_list = {}
for entry in entries_list:
if key in case_list:
case_list[key1].append(value)
else:
case_list[key1] = [value]
I also have the similar problem, and later on I found it is because I changed my hostname (not localhost
).
Therefore I get it resolved by specifying the --host=127.0.0.1
mysql -p mydatabase --host=127.0.0.1
Use subset within ggplot
ggplot(data = subset(df, ID == "P1" | ID == "P2") +
aes(Value1, Value2, group=ID, colour=ID) +
geom_line()
Just Make a single class like, everything will be fine with this:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyCorsConfig implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, enctype");
response.setHeader("Access-Control-Max-Age", "3600");
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig config) throws ServletException {
}
}
Try like
var hasName = 'N';
if (name == "true") {
hasName = 'Y';
}
Or even try with ternary operator
like
var hasName = (name == "true") ? "Y" : "N" ;
Even simply you can try like
var hasName = (name) ? "Y" : "N" ;
Since name has either Yes
or No
but iam not sure with it.
With vim from command line:
vim -c "set encoding=utf8" -c "set fileencoding=utf8" -c "wq" filename
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
BMS business month start frequency
CBMS custom business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA, BY business year end frequency
AS, YS year start frequency
BAS, BYS business year start frequency
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds
See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.
Note that there isn't a list of all the different how
options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how
by name.
Aditya or others, can you join or match up t2 with t1 in your example, i.e. translated to my code,
with t1 as (select * from AA where FIRSTNAME like 'Kermit'),
t2 as (select * from BB B join t1 on t1.FIELD1 = B.FIELD1)
I am not clear whether only WHERE is supported for joining, or what joining approach is supported within the 2nd WITH entity. Some of the examples have the WHERE A=B down in the body of the select "below" the WITH clauses.
The error I'm getting following these WITH declarations is the identifiers (field names) in B are not recognized, down in the body of the rest of the SQL. So the WITH syntax seems to run OK, but cannot access the results from t2.
#Implement a generic return stack for functions:
STACK=()
push() {
STACK+=( "${1}" )
}
pop() {
export $1="${STACK[${#STACK[@]}-1]}"
unset 'STACK[${#STACK[@]}-1]';
}
#Usage:
my_func() {
push "Hello world!"
push "Hello world2!"
}
my_func ; pop MESSAGE2 ; pop MESSAGE1
echo ${MESSAGE1} ${MESSAGE2}
on windows 8, it worked for me using :
npm install -g node-gyp -msvs_version=2012
then
npm install -g restify
I'm assuming you're using Windows, and GitBASH.
You can just delete the folder "C:...\project" with no adverse effects.
Then in git bash, you can do cd c\:
. This changes the directory you're working in to C:\
Then you can do git clone [url]
This will create a folder called "project" on C:\ with the contents of the repo.
If you'd like to name it something else, you can do
git clone [url] [something else]
For example
cd c\:
git clone [email protected]:username\repo.git MyRepo
This would create a folder at "C:\MyRepo" with the contents of the remote repository.
strcpy example:
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]="Sample string" ;
char str2[40] ;
strcpy (str2,str1) ;
printf ("str1: %s\n",str1) ;
return 0 ;
}
Output: str1: Sample string
Your case:
A simple =
operator should do the job.
string str1="Sample string" ;
string str2 = str1 ;
Another possible solution:
<div>
<h2 align="center">
San Andreas: Multiplayer
</h2>
<div align="center">
<font size="+1"><em class="heading_description">15 pence per
slot</em></font> <img src=
"http://fhers.com/images/game_servers/sa-mp.jpg" class=
"alignleft noTopMargin" style="width: 188px;" /> <a href="gfh"
class="order-small"><span>order</span></a>
</div>
</div>
Also helpful as well.
If you want case-insensitive comparison, use lower
or upper
:
if name.lower() == "jesse":
It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.
If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate
and colMeans
, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.
However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for
loop.
> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 >
So in your case, if you just wanted to print the mean of your Tandem
object 5 times:
for (ii in 1:5) { Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL) TandemMean <- mean(Tandem) print(TandemMean) }
As mentioned above, replicate
is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.
set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) { tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) } tandem[1] tandem[100] tandem[20:25]
...creates this output:
> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { + tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } > > tandem[1] [[1]] [1] 1.511923 > tandem[100] [[1]] [1] 1.496777 > tandem[20:25] [[1]] [1] 1.500669 [[2]] [1] 1.487552 [[3]] [1] 1.503409 [[4]] [1] 1.501362 [[5]] [1] 1.499728 [[6]] [1] 1.492798 >
If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
// Create a new X509TrustManager
sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
.sslContext(sslContext).build();
return client;
private TrustManager[] getTrustManager() {
return new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
};
}
I am starting a new C++ project and started looking for the latest in C++ style. I ended up here regarding file naming and I thought that I would share how I came up with my choice. Here goes:
Stroustrup sees this more as a business consideration than a technical one.
Following his advice, let's check what the toolchains expect.
For UNIX/Linux, you may interpret the following default GNU make rules as favoring the .cc filename suffix, as .cpp and .C rules are just aliases:
$ make -p | egrep COMPILE[^=]+=
COMPILE.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
COMPILE.cpp = $(COMPILE.cc)
COMPILE.C = $(COMPILE.cc)
(Note: there is no default COMPILE.cxx alias)
So if you are targeting UNIX/Linux, both .cc and .cpp are very good options.
When targeting Windows, you are looking for trouble with .C, as its file system is case-insensitive. And it may be important for you to note that Visual Studio favors the .cpp suffix
When targeting macOS, note that Xcode prefers .cpp/.hpp (just checked on Xcode 10.1). You can always change the header template to use .h.
For what it is worth, you can also base your decision on the code bases that you like. Google uses .cc and LLVM libc++ uses .cpp, for instance.
What about header files? They are compiled in the context of a C or C++ file, so there is no compiler or build system need to distinguish .h from .hpp. Syntax highlighting and automatic indentation by your editor/IDE can be an issue, however, but this is fixed by associating all .h files to a C++ mode. As an example, my emacs config on Linux loads all .h files in C++ mode and it edits C headers just fine. Beyond that, when mixing C and C++, you can follow this advice.
My personal conclusion: .cpp/.h is the path of least resistance.
For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;
You will need the sudo password.
sudo nano /etc/nginx/conf.d/uploads.conf
Replace contents with the following;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
client_max_body_size 24M;
client_body_buffer_size 128k;
client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;
// to string
String text = textField.getText();
// to JTextField
textField.setText(text);
You can also create a new text field: new JTextField(text)
Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.
Reference: javadocs of JTextField
Use the Pandas library to create a dataframe of the csv data.
Name the fields either by including them in the csv file's first line or in code by using the dataframe's columns method.
Then create a list of model instances.
Finally use the django method .bulk_create() to send your list of model instances to the database table.
The read_csv function in pandas is great for reading csv files and gives you lots of parameters to skip lines, omit fields, etc.
import pandas as pd
tmp_data=pd.read_csv('file.csv',sep=';')
#ensure fields are named~ID,Product_ID,Name,Ratio,Description
#concatenate name and Product_id to make a new field a la Dr.Dee's answer
products = [
Product(
name = tmp_data.ix[row]['Name']
description = tmp_data.ix[row]['Description'],
price = tmp_data.ix[row]['price'],
)
for row in tmp_data['ID']
]
Product.objects.bulk_create(products)
I was using the answer by mmrs151 but saving each row (instance) was very slow and any fields containing the delimiting character (even inside of quotes) were not handled by the open() -- line.split(';') method.
Pandas has so many useful caveats, it is worth getting to know
I know many have already posted some good answers. However I want to suggest one nice and easy method without importing any library.
l = [(2, 3), (3, 4), (2, 4)]
l.sort(key = lambda x: (-x[0], -x[1]) )
print(l)
l.sort(key = lambda x: (x[0], -x[1]) )
print(l)
Output will be
[(3, 4), (2, 4), (2, 3)]
[(2, 4), (2, 3), (3, 4)]
The output will be sorted based on the order of the parameters we provided in the tuple format
I am using below solution but for that you have to install sshpass
If its not already installed, install it using sudo apt install sshpass
Now you can do this,
sshpass -p *YourPassword* shh root@IP
You can create a bash alias as well so that you don't have to run the whole command again and again. Follow below steps
cd ~
sudo nano .bash_profile
at the end of the file add below code
mymachine() { sshpass -p *YourPassword* shh root@IP }
source .bash_profile
Now just run mymachine
command from terminal and you'll enter your machine without password prompt.
Note:
mymachine
can be any command of your choice.Your compiler just tried to compile the file named foo.cc
. Upon hitting line number line
, the compiler finds:
#include "bar"
or
#include <bar>
The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar
. For an explanation of the difference between the versions of the include statement look here.
g++
has an option -I
. It lets you add include search paths to the command line. Imagine that your file bar
is in a folder named frobnicate
, relative to foo.cc
(assume you are compiling from the directory where foo.cc
is located):
g++ -Ifrobnicate foo.cc
You can add more include-paths; each you give is relative to the current directory. Microsoft's compiler has a correlating option /I
that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.
Now imagine you have multiple version of bar
in different folders, given:
// A/bar
#include<string>
std::string which() { return "A/bar"; }
// B/bar
#include<string>
std::string which() { return "B/bar"; }
// C/bar
#include<string>
std::string which() { return "C/bar"; }
// foo.cc
#include "bar"
#include <iostream>
int main () {
std::cout << which() << std::endl;
}
The priority with #include "bar"
is leftmost:
$ g++ -IA -IB -IC foo.cc
$ ./a.out
A/bar
As you see, when the compiler started looking through A/
, B/
and C/
, it stopped at the first or leftmost hit.
This is true of both forms, include <>
and incude ""
.
#include <bar>
and #include "bar"
Usually, the #include <xxx>
makes it look into system folders first, the #include "xxx"
makes it look into the current or custom folders first.
E.g.:
Imagine you have the following files in your project folder:
list
main.cc
with main.cc
:
#include "list"
....
For this, your compiler will #include
the file list
in your project folder, because it currently compiles main.cc
and there is that file list
in the current folder.
But with main.cc
:
#include <list>
....
and then g++ main.cc
, your compiler will look into the system folders first, and because <list>
is a standard header, it will #include
the file named list
that comes with your C++ platform as part of the standard library.
This is all a bit simplified, but should give you the basic idea.
<>
/""
-priorities and -I
According to the gcc-documentation, the priority for include <>
is, on a "normal Unix system", as follows:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; [...].
The documentation also states:
You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.
To continue our #include<list> / #include"list"
example (same code):
g++ -I. main.cc
and
#include<list>
int main () { std::list<int> l; }
and indeed, the -I.
prioritizes the folder .
over the system includes and we get a compiler error.
You can use a range to do that.
git log master..
If you've checked out your my_experiment
branch. This will compare where master
is at to HEAD
(the tip of my_experiment
).
I might be late in the game, but how about:
public event Action<MyEvent> EventTriggered = delegate { };
private void Trigger(MyEvent e)
{
EventTriggered(e);
}
Setting the event to an anonymous delegate avoids for me to check to see if the event isn't null.
I find this comes in handy when using MVVM, like when using ICommand.CanExecute Method.
Just to confirm answers here, my resolution was to copy the DLL that was not loading AND the ocx file that accompanied it to the system32 folder, that resolved my issue.
Check this fiddle. You are going to need to take a look at using border-collapse and border-spacing. There are some quirks for IE (as usual). This is based on an answer to this question.
table.test td {
background-color: lime;
margin: 12px 12px 12px 12px;
padding: 12px 12px 12px 12px;
}
table.test {
border-collapse: separate;
border-spacing: 10px;
*border-collapse: expression('separate', cellSpacing='10px');
}
_x000D_
<table class="test">
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
_x000D_
Try this:
<select id="nameSelect" onfocus="javascript:document.getElementById('nameSelect').selectedIndex=-1;" onchange="doSomething(this);">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
I completely agree with @Peter Rasmussen.
Design patterns provide general solution to commonly occurring design problem.
I would like you to follow below approach.
Useful links:
sourcemaking : Explains intent, structure and checklist beautifully in multiple languages including C++ and Java
wikipedia : Explains structure, UML diagram and working examples in multiple languages including C# and Java .
Check list and Rules of thumb in each sourcemakding design-pattern provides alram bell you are looking for.
As specified here You can update the index:
git update-index --assume-unchanged /path/to/file
By doing this, the files will not show up in git status
or git diff
.
To begin tracking the files again you can run:
git update-index --no-assume-unchanged /path/to/file
You can also say:
cut -d\ -f 2
Note that there are two spaces after the backslash.
time = Time.now.to_s
time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")
for increment decrement month use << >> operators
examples
datetime_month_before = DateTime.parse(time) << 1
datetime_month_before = DateTime.now << 1
I think you can go with 3 steps:
git clone
git submodule init
git submodule update
There is no single function that does what you want. Your definition of shift is slightly different than what most people are doing. The ways to shift an array are more commonly looped:
>>>xs=np.array([1,2,3,4,5])
>>>shift(xs,3)
array([3,4,5,1,2])
However, you can do what you want with two functions.
Consider a=np.array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
:
def shift2(arr,num):
arr=np.roll(arr,num)
if num<0:
np.put(arr,range(len(arr)+num,len(arr)),np.nan)
elif num > 0:
np.put(arr,range(num),np.nan)
return arr
>>>shift2(a,3)
[ nan nan nan 0. 1. 2. 3. 4. 5. 6.]
>>>shift2(a,-3)
[ 3. 4. 5. 6. 7. 8. 9. nan nan nan]
After running cProfile on your given function and the above code you provided, I found that the code you provided makes 42 function calls while shift2
made 14 calls when arr is positive and 16 when it is negative. I will be experimenting with timing to see how each performs with real data.
You can do it easily with regex:
string subject = "(913)-444-5555";
string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555"
The code should be :
#include <iostream>
using namespace std;
int main() {
cout << "Hello World";
return 0;
}
Or maybe :
#include <iostream>
int main() {
std::cout << "Hello World";
return 0;
}
Just a quick note: I have deleted the system command, because I heard it's not a good practice to use it. (but of course, you can add it for this kind of program)
Use wmic computersystem get TotalPhysicalMemory
. E.g.:
C:\>wmic computersystem get TotalPhysicalMemory
TotalPhysicalMemory
4294500352
I found this very difficult to get an answer to but eventually figured it out. So I will write the steps below.
Before you setup your connection string in code, ensure you actually can access your database. Start obviously by logging into the database server using SSMS (Sql Server Management Studio or it's equivalent in other databases) locally to ensure you have access using whatever details you intend to use.
Next (if needed), if you are trying to access the database on a separate server, ensure you can do likewise in SSMS. So setup SSMS on a computer and ensure you can access the server with the username and password to that database server.
If you don't get the above 2 right, you are simply wasting your time as you cant access the database. This can either be because the user you setup is wrong, doesn't have remote access enabled (if needed), or the ports are not opened (if needed), among many other reasons but these being the most common.
Once you have verified that you can access the database using SSMS. The next step, just for the sake of automating the process and avoiding mistakes, is to let the system do the work for you.
Now go into the web config, and magically, you will see nice clean working connection string there with all the details you need.
{ Below was part of an old post so you can ignore this, I leave it in for reference as its the most basic way to access the database from only code behind. Please scroll down and continue from step 2 below. }
Lets assume the above steps start you off with something like the following as your connection string in the code behind:
string conString = "Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;";
This step is very important. Make sure you have the above format of connection string working before taking the following steps. Make sure you actually can access your data using some form of sql command text which displays some data from a table in labels or text boses or whatever, as this is the simplest way to do a connection string.
Once you are sure the above style works its now time to take the next steps:
1. Export your string literal (the stuff in the quotes, including the quotes) to the following section of the web.config file (for multiple connection strings, just do multiple lines:
<configuration>
<connectionStrings>
<add name="conString" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
<add name="conString2" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
<add name="conString3" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
{ The above was part of an old post, after doing the top 3 steps this whole process will be done for you, so you can ignore it. I just leave it here for my own reference. }
2. Now add the following line of code to the C# code behind, prefrably just under the class definition (i.e. not inside a method). This points to the root folder of your project. Essentially it is the project name. This is usually the location of the web.config file (in this case my project is called MyProject.
static Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/MyProject");
3. Now add the following line of code to the C# code behind. This sets up a string constant to which you can refer in many places throughout your code should you need a conString in different methods.
const string CONSTRINGNAME = "conString";
4. Next add the following line of code to the C# code behind. This gets the connection string from the web.config file with the name conString (from the constant above)
ConnectionStringSettings conString = rootWebConfig.ConnectionStrings.ConnectionStrings[CONSTRINGNAME];
5. Finally, where you origionally would have had something similar to this line of code:
SqlConnection con = new SqlConnection(conString)
you will replace it with this line of code:
SqlConnection con = new SqlConnection(conString.ConnectionString)
After doing these 5 steps your code should work as it did before. Hense the reason you test the constring first in its origional format so you know if it is a problem with the connection string or if it is a problem with the code.
I am new to C#, ASP.Net and Sql Server. So I am sure there must be a better way to do this code. I also would appreicate feedback on how to improve these steps if possible. I have looked all over for something like this but I eventually figured it out after many weeks of hard work. Looking at it myself, I still think, there must be an easier way.
I hope this is helpful.
DWORD
is not a C++ type, it's defined in <windows.h>
.
The reason is that DWORD
has a specific range and format Windows functions rely on, so if you require that specific range use that type. (Or as they say "When in Rome, do as the Romans do.") For you, that happens to correspond to unsigned int
, but that might not always be the case. To be safe, use DWORD
when a DWORD
is expected, regardless of what it may actually be.
For example, if they ever changed the range or format of unsigned int
they could use a different type to underly DWORD
to keep the same requirements, and all code using DWORD
would be none-the-wiser. (Likewise, they could decide DWORD
needs to be unsigned long long
, change it, and all code using DWORD
would be none-the-wiser.)
Also note unsigned int
does not necessary have the range 0 to 4,294,967,295. See here.
Not sure its faster with VBA - the fastest way to do it in the normal Excel programm would be:
Ctrl-G
A1:X50 Enter
Delete
Unless you have to do this very often, entering and then triggering the VBAcode is more effort.
And in case you only want to delete formulas or values, you can insert Ctrl-G, Alt-S
to select Goto Special and here select Formulas or Values.
[Update]
I've just realized why you weren't receiving results back... you have a missing line in your Deserialize
method. You were forgetting to assign the results to your obj
:
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
Also, just for reference, here is the Serialize
method :
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
Edit
If you want to use Json.NET here are the equivalent Serialize/Deserialize methods to the code above..
Deserialize:
JsonConvert.DeserializeObject<T>(string json);
Serialize:
JsonConvert.SerializeObject(object o);
This are already part of Json.NET so you can just call them on the JsonConvert class.
Link: Serializing and Deserializing JSON with Json.NET
Now, the reason you're getting a StackOverflow is because of your Properties
.
Take for example this one :
[DataMember]
public string unescapedUrl
{
get { return unescapedUrl; } // <= this line is causing a Stack Overflow
set { this.unescapedUrl = value; }
}
Notice that in the getter
, you are returning the actual property (ie the property's getter is calling itself over and over again), and thus you are creating an infinite recursion.
Properties (in 2.0) should be defined like such :
string _unescapedUrl; // <= private field
[DataMember]
public string unescapedUrl
{
get { return _unescapedUrl; }
set { _unescapedUrl = value; }
}
You have a private field and then you return the value of that field in the getter, and set the value of that field in the setter.
Btw, if you're using the 3.5 Framework, you can just do this and avoid the backing fields, and let the compiler take care of that :
public string unescapedUrl { get; set;}
I've done it with two annotations for test class: @RunWith(SpringRunner.class)
and @SpringBootTest
.
Example:
@RunWith(SpringRunner.class )
@SpringBootTest
public class ProtocolTransactionServiceTest {
@Autowired
private ProtocolTransactionService protocolTransactionService;
}
@SpringBootTest
loads the whole context, which was OK in my case.
You can use this code for connect and request using http and json
try {
URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
+ "&key="+key
+ "&access_token=" + access_token);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I ran into this nasty stack trace with the new Android Architecture Components recently. Essentially, I have a list of items in my ViewModel that are observed by my Fragment, using LiveData. When the ViewModel posts a new value for the data, the Fragment updates the adapter, passing in these new data elements and notifying the adapter that there have been changes.
Unfortunately, when passing in the new data elements to the adapter, I failed to account for the fact that both the ViewModel and the Adapter would be pointing to the same object reference! Meaning that if I update the data and call postValue()
from within the ViewModel, there's a very small window where the data could be updated and the adapter not yet notified!
My fix was to instantiate a fresh copy of the elements when passed in to the adapter:
mList = new ArrayList<>(passedList);
With this super easy fix you can be ensured your adapter data will not change until right before your adapter is notified.
It turns out that my understanding of the error message was wrong. I'd say it features very poor choice of words. Googling around shown me someone else misunderstood the message exactly like I did - see PHP bug #66763.
After totally unhelpful "This is the way the RMs wanted it to be." response to that bug by Mike, Tyrael explains that setting it to "-1" doesn't make just the warning to go away. It does the right thing, i.e. it completely disables populating the culprit variable. Turns out that having it set to 0 STILL populates data under some circumstances. Talk about bad design! To cite PHP RFC:
Change always_populate_raw_post_data INI setting to accept three values instead of two.
- -1: The behavior of master; don't ever populate $GLOBALS[HTTP_RAW_POST_DATA]
- 0/off/whatever: BC behavior (populate if content-type is not registered or request method is other than POST)
- 1/on/yes/true: BC behavior (always populate $GLOBALS[HTTP_RAW_POST_DATA])
So yeah, setting it to -1 not only avoids the warning, like the message said, but it also finally disables populating this variable, which is what I wanted.
Use the where
command. The first result in the list is the one that will execute.
C:\> where notepad C:\Windows\System32\notepad.exe C:\Windows\notepad.exe
According to this blog post, where.exe
is included with Windows Server 2003 and later, so this should just work with Vista, Win 7, et al.
On Linux, the equivalent is the which
command, e.g. which ssh
.
Interesting, this is probably a "feature request" (ie bug) for jQuery. The jQuery click event only triggers the click action (called onClick event on the DOM) on the element if you bind a jQuery event to the element. You should go to jQuery mailing lists ( http://forum.jquery.com/ ) and report this. This might be the wanted behavior, but I don't think so.
EDIT:
I did some testing and what you said is wrong, even if you bind a function to an 'a' tag it still doesn't take you to the website specified by the href attribute. Try the following code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
/* Try to dis-comment this:
$('#a').click(function () {
alert('jQuery.click()');
return true;
});
*/
});
function button_onClick() {
$('#a').click();
}
function a_onClick() {
alert('a_onClick');
}
</script>
</head>
<body>
<input type="button" onclick="button_onClick()">
<br>
<a id='a' href='http://www.google.com' onClick="a_onClick()"> aaa </a>
</body>
</html>
It never goes to google.com unless you directly click on the link (with or without the commented code). Also notice that even if you bind the click event to the link it still doesn't go purple once you click the button. It only goes purple if you click the link directly.
I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.
Briefly bitmask helps to manipulate position of multiple values. There is a good example here ;
Bitflags are a method of storing multiple values, which are not mutually exclusive, in one variable. You've probably seen them before. Each flag is a bit position which can be set on or off. You then have a bunch of bitmasks #defined for each bit position so you can easily manipulate it:
#define LOG_ERRORS 1 // 2^0, bit 0
#define LOG_WARNINGS 2 // 2^1, bit 1
#define LOG_NOTICES 4 // 2^2, bit 2
#define LOG_INCOMING 8 // 2^3, bit 3
#define LOG_OUTGOING 16 // 2^4, bit 4
#define LOG_LOOPBACK 32 // and so on...
// Only 6 flags/bits used, so a char is fine
unsigned char flags;
// initialising the flags
// note that assigning a value will clobber any other flags, so you
// should generally only use the = operator when initialising vars.
flags = LOG_ERRORS;
// sets to 1 i.e. bit 0
//initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3
// setting one flag on, leaving the rest untouched
// OR bitmask with the current value
flags |= LOG_INCOMING;
// testing for a flag
// AND with the bitmask before testing with ==
if ((flags & LOG_WARNINGS) == LOG_WARNINGS)
...
// testing for multiple flags
// as above, OR the bitmasks
if ((flags & (LOG_INCOMING | LOG_OUTGOING))
== (LOG_INCOMING | LOG_OUTGOING))
...
// removing a flag, leaving the rest untouched
// AND with the inverse (NOT) of the bitmask
flags &= ~LOG_OUTGOING;
// toggling a flag, leaving the rest untouched
flags ^= LOG_LOOPBACK;
**
WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and all others are unset. To test for a single flag you need to use & and == :
**
if (flags == LOG_WARNINGS) //DON'T DO THIS
...
if ((flags & LOG_WARNINGS) == LOG_WARNINGS) // The right way
...
if ((flags & (LOG_INCOMING | LOG_OUTGOING)) // Test for multiple flags set
== (LOG_INCOMING | LOG_OUTGOING))
...
You can also search C++ Triks
values = ['A', 'B', 'C', 'D', 'E']
values[0] # returns 'A'
values[2] # returns 'C'
# etc.
To get an attribute to show a specific value based on a boolean check, or be omitted entirely if the boolean check failed, I used the following:
ng-attr-example="{{params.type == 'test' ? 'itWasTest' : undefined }}"
Example usage:
<div ng-attr-class="{{params.type == 'test' ? 'itWasTest' : undefined }}">
Would output <div class="itWasTest">
or <div>
based on the value of params.type
Java 1.8 (as well as Groovy and Scala) has a thing called "Interface Defender Methods", which are interfaces with pre-defined default method bodies. By implementing multiple interfaces that use defender methods, you could effectively, in a way, extend the behavior of two interface objects.
Also, in Groovy, using the @Delegate annotation, you can extend behavior of two or more classes (with caveats when those classes contain methods of the same name). This code proves it:
class Photo {
int width
int height
}
class Selection {
@Delegate Photo photo
String title
String caption
}
def photo = new Photo(width: 640, height: 480)
def selection = new Selection(title: "Groovy", caption: "Groovy", photo: photo)
assert selection.title == "Groovy"
assert selection.caption == "Groovy"
assert selection.width == 640
assert selection.height == 480
No. There isn't..
But, for development there is such a link on the jQuery code site.
Just add:
import os
in the beginning, before:
from settings import PROJECT_ROOT
This will import the python's module os, which apparently is used later in the code of your module without being imported.
First I installed the Nvidia driver.
Next I installed cuda.
Ater that I got the "Driver/library version mismatch" ERROR but I could see the cuda version so I purged the Nvidia driver and reinstall it.
Then it worked correctly.
Set the property RetainSameConnection
on the Connection Manager
to True
so that temporary table created in one Control Flow task can be retained in another task.
Here is a sample SSIS package written in SSIS 2008 R2
that illustrates using temporary tables.
Create a stored procedure that will create a temporary table named ##tmpStateProvince
and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora
Use the below create stored procedure script.
USE Sora;
GO
CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
DROP TABLE ##tmpStateProvince;
CREATE TABLE ##tmpStateProvince
(
CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
);
INSERT INTO ##tmpStateProvince
(CountryCode, StateCode, Name)
VALUES
('CA', 'AB', 'Alberta'),
('US', 'CA', 'California'),
('DE', 'HH', 'Hamburg'),
('FR', '86', 'Vienne'),
('AU', 'SA', 'South Australia'),
('VI', 'VI', 'Virgin Islands');
END
GO
Create a table named dbo.StateProvince
that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.
USE Sora;
GO
CREATE TABLE dbo.StateProvince
(
StateProvinceID int IDENTITY(1,1) NOT NULL
, CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
([StateProvinceID] ASC)
) ON [PRIMARY];
GO
Create an SSIS package using Business Intelligence Development Studio (BIDS)
. Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection...
to create a new connection to access SQL Server 2008 R2 database.
Click New...
on Configure OLE DB Connection Manager.
Perform the following actions on the Connection Manager dialog.
Native OLE DB\SQL Server Native Client 10.0
from Provider since the package will connect to SQL Server 2008 R2 databaseMACHINENAME\INSTANCE
Use Windows Authentication
from Log on to the server section or whichever you prefer.Select or enter a database name
, the sample uses the database name Sora
.Test Connection
OK
on the Test connection succeeded message.OK
on Connection ManagerThe newly created data connection will appear on Configure OLE DB Connection Manager. Click OK
.
OLE DB connection manager KIWI\SQLSERVER2008R2.Sora
will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties
Set the property RetainSameConnection
on the connection KIWI\SQLSERVER2008R2.Sora
to the value True
.
Right-click anywhere inside the package and then click Variables
to view the variables pane. Create the following variables.
A new variable named PopulateTempTable
of data type String
in the package scope SO_5631010
and set the variable with the value EXEC dbo.PopulateTempTable
.
A new variable named FetchTempData
of data type String
in the package scope SO_5631010
and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince
Drag and drop an Execute SQL Task
on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.
On the General
page of the Execute SQL Task Editor, perform the following actions.
Create and populate temp table
OLE DB
KIWI\SQLSERVER2008R2.Sora
Variable
from SQLSourceTypeUser::PopulateTempTable
from SourceVariableOK
Drag and drop a Data Flow Task
onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table
. Connect the green arrow from the Execute SQL Task to the Data Flow Task.
Double-click the Data Flow Task
to switch to Data Flow tab. Drag and drop an OLE DB Source
onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.
On the Connection Manager
page of the OLE DB Source Editor, perform the following actions.
KIWI\SQLSERVER2008R2.Sora
from OLE DB Connection ManagerSQL command from variable
from Data access modeUser::FetchTempData
from Variable nameColumns
pageClicking Columns
page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince
specified in the source command variable does not exist and SSIS is unable to read the column definition.
To fix the error, execute the statement EXEC dbo.PopulateTempTable
using SQL Server Management Studio (SSMS) on the database Sora
so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns
page on OLE DB Source Editor, you will see the column information. Click OK
.
Drag and drop OLE DB Destination
onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination
to open OLE DB Destination Editor.
On the Connection Manager
page of the OLE DB Destination Editor, perform the following actions.
KIWI\SQLSERVER2008R2.Sora
from OLE DB Connection ManagerTable or view - fast load
from Data access mode[dbo].[StateProvince]
from Name of the table or the viewMappings
pageClick Mappings
page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK
. Column StateProvinceID
does not have a matching input column and it is defined as an IDENTITY
column in database. Hence, no mapping is required.
Data Flow tab should look something like this after configuring all the components.
Click the OLE DB Source
on Data Flow tab and press F4 to view Properties
. Set the property ValidateExternalMetadata
to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.
Execute the query select * from dbo.StateProvince
in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.
Execute the package. Control Flow shows successful execution.
In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.
Execute the query select * from dbo.StateProvince
in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.
The above example illustrated how to create and use temporary table within a package.
JavaScript objects can only use strings as keys (anything else is converted to a string).
You could, alternatively, maintain an array which indexes the objects in question, and use its index string as a reference to the object. Something like this:
var ObjectReference = [];
ObjectReference.push(obj);
set['ObjectReference.' + ObjectReference.indexOf(obj)] = true;
Obviously it's a little verbose, but you could write a couple of methods that handle it and get and set all willy nilly.
Edit:
Your guess is fact -- this is defined behaviour in JavaScript -- specifically a toString conversion occurs meaning that you can can define your own toString function on the object that will be used as the property name. - olliej
This brings up another interesting point; you can define a toString method on the objects you want to hash, and that can form their hash identifier.
Use:
:ls
- to list buffers:bd#n
- to close buffer where #n is the buffer number (use ls
to get it)Examples:
to delete buffer 2:
:bd2
You cannot change the DataType after the Datatable is filled with data. However, you can clone the Data table, change the column type and load data from previous data table to the cloned table as shown below.
DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
please use it like this first thing give a class name to tag p like "myp"
then on use the following code
$(document).ready(function() {
$(".myp").click(function() {
$(this).children(":first").toggleClass("classname"); // this will access the span.
})
})
I suggest the use of htop, as a better alternative to top.
All of this works for me:
@Echo Off
Echo Directory = %~dp0
Echo Object Name With Quotations=%0
Echo Object Name Without Quotes=%~0
Echo Bat File Drive = %~d0
Echo Full File Name = %~n0%~x0
Echo File Name Without Extension = %~n0
Echo File Extension = %~x0
Pause>Nul
Output:
Directory = D:\Users\Thejordster135\Desktop\Code\BAT\
Object Name With Quotations="D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat"
Object Name Without Quotes=D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat
Bat File Drive = D:
Full File Name = Path.bat
File Name Without Extension = Path
File Extension = .bat
I use __get
(and public properties) as much as possible, because they make code much more readable. Compare:
this code unequivocally says what i'm doing:
echo $user->name;
this code makes me feel stupid, which i don't enjoy:
function getName() { return $this->_name; }
....
echo $user->getName();
The difference between the two is particularly obvious when you access multiple properties at once.
echo "
Dear $user->firstName $user->lastName!
Your purchase:
$product->name $product->count x $product->price
"
and
echo "
Dear " . $user->getFirstName() . " " . $user->getLastName() . "
Your purchase:
" . $product->getName() . " " . $product->getCount() . " x " . $product->getPrice() . " ";
Whether $a->b
should really do something or just return a value is the responsibility of the callee. For the caller, $user->name
and $user->accountBalance
should look the same, although the latter may involve complicated calculations. In my data classes i use the following small method:
function __get($p) {
$m = "get_$p";
if(method_exists($this, $m)) return $this->$m();
user_error("undefined property $p");
}
when someone calls $obj->xxx
and the class has get_xxx
defined, this method will be implicitly called. So you can define a getter if you need it, while keeping your interface uniform and transparent. As an additional bonus this provides an elegant way to memorize calculations:
function get_accountBalance() {
$result = <...complex stuff...>
// since we cache the result in a public property, the getter will be called only once
$this->accountBalance = $result;
}
....
echo $user->accountBalance; // calculate the value
....
echo $user->accountBalance; // use the cached value
Bottom line: php is a dynamic scripting language, use it that way, don't pretend you're doing Java or C#.
The fastest way to do file I/O from C# is to use the Windows ReadFile and WriteFile functions. I have written a C# class that encapsulates this capability as well as a benchmarking program that looks at differnet I/O methods, including BinaryReader and BinaryWriter. See my blog post at:
http://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/
Such kind of error normally happens when you try using functions like php_info() wrongly.
<?php
php_info(); // 500 error
phpinfo(); // Works correctly
?>
A close look at your code will be better.
Since the back button is a function of the browser, it can be difficult to change the default functionality. There are some work arounds though. Take a look at this article:
http://www.irt.org/script/311.htm
Typically, the need to disable the back button is a good indicator of a programming issue/flaw. I would look for an alternative method like setting a session variable or a cookie that stores whether the form has already been submitted.
Simpler and a Standard solution to increment the number and to retain the dot at the end. Even if you get the css right, it will not work if your HTML is not correct. see below.
ol {
counter-reset: item;
}
ol li {
display: block;
}
ol li:before {
content: counters(item, ". ") ". ";
counter-increment: item;
}
ol {
counter-reset: item;
li {
display: block;
&:before {
content: counters(item, ". ") ". ";
counter-increment: item
}
}
}
If you add the child make sure the it is under the parent li
.
<!-- WRONG -->
<ol>
<li>Parent 1</li> <!-- Parent is Individual. Not hugging -->
<ol>
<li>Child</li>
</ol>
<li>Parent 2</li>
</ol>
<!-- RIGHT -->
<ol>
<li>Parent 1
<ol>
<li>Child</li>
</ol>
</li> <!-- Parent is Hugging the child -->
<li>Parent 2</li>
</ol>
Here
{int y=((year-1)%100);int c=(year-1)/100;}
you declare and initialize the variables y, c
, but you don't used them at all before they run out of scope. That's why you get the unused
message.
Later in the function, y, c
are undeclared, because the declarations you made only hold inside the block they were made in (the block between the braces {...}
).
Some of these answers don't address the CORS issue, or don't make it obvious where you place the code snippets to make the communication possible.
Here is a concrete example. Say I want to click a button on the parent page, and have that do something inside the iframe. Here is how I would do it.
parent_frame.html
<button id='parent_page_button' onclick='call_button_inside_frame()'></button>
function call_button_inside_frame() {
document.getElementById('my_iframe').contentWindow.postMessage('foo','*');
}
iframe_page.html
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if(event) {
click_button_inside_frame();
}
}
function click_button_inside_frame() {
document.getElementById('frame_button').click();
}
To go the other direction (click button inside iframe to call method outside iframe) just switch where the code snippet live, and change this:
document.getElementById('my_iframe').contentWindow.postMessage('foo','*');
to this:
window.parent.postMessage('foo','*')
You can do it without writing any code at all :) You just need to set the default value for the column in the database. You can do this in your migrations. For example:
create_table :projects do |t|
t.string :status, :null => false, :default => 'P'
...
t.timestamps
end
Hope that helps.
Because interfaces are in inheritance structure, and static methods don't inherit well.
Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1
This takes the value from an unbound custom field, processes, and saves it into my real description field:
class WidgetForm(forms.ModelForm):
extra_field = forms.CharField(required=False)
def processData(self, input):
# example of error handling
if False:
raise forms.ValidationError('Processing failed!')
return input + " has been processed"
def save(self, commit=True):
extra_field = self.cleaned_data.get('extra_field', None)
# self.description = "my result" note that this does not work
# Get the form instance so I can write to its fields
instance = super(WidgetForm, self).save(commit=commit)
# this writes the processed data to the description field
instance.description = self.processData(extra_field)
if commit:
instance.save()
return instance
class Meta:
model = Widget
fields = "__all__"
Answering the question in your title, you can query sys.tables
or sys.objects
where type = 'U'
to check for the existence of a table. You can also use OBJECT_ID('table_name', 'U'). If it returns a non-null value then the table exists:
IF (OBJECT_ID('dbo.My_Table', 'U') IS NULL)
BEGIN
CREATE TABLE dbo.My_Table (...)
END
You can do the same for databases with DB_ID():
IF (DB_ID('My_Database') IS NULL)
BEGIN
CREATE DATABASE My_Database
END
If you want to create the database and then start using it, that needs to be done in separate batches. I don't know the specifics of your case, but there shouldn't be many cases where this isn't possible. In a SQL script you can use GO
statements. In an application it's easy enough to send across a new command after the database is created.
The only place that you might have an issue is if you were trying to do this in a stored procedure and creating databases on the fly like that is usually a bad idea.
If you really need to do this in one batch, you can get around the issue by using EXEC to get around the parsing error of the database not existing:
CREATE DATABASE Test_DB2
IF (OBJECT_ID('Test_DB2.dbo.My_Table', 'U') IS NULL)
BEGIN
EXEC('CREATE TABLE Test_DB2.dbo.My_Table (my_id INT)')
END
EDIT: As others have suggested, the INFORMATION_SCHEMA.TABLES
system view is probably preferable since it is supposedly a standard going forward and possibly between RDBMSs.
You could use a CountDownLatch
from the java.util.concurrent
package. It is very useful when waiting for one or more threads to complete before continuing execution in the awaiting thread.
For example, waiting for three tasks to complete:
CountDownLatch latch = new CountDownLatch(3);
...
latch.await(); // Wait for countdown
The other thread(s) then each call latch.countDown()
when complete with the their tasks. Once the countdown is complete, three in this example, the execution will continue.
If your file is a large file, 50MB+, then I recommend you use sqlcmd, the command line utility that comes bundled with SQL Server. It is easy to use and it handles large files well. I tried it yesterday with a 22GB file using the following command:
sqlcmd -S SERVERNAME\INSTANCE_NAME -i C:\path\mysqlfile.sql -o C:\path\output_file.txt
The command above assumes that your server name is SERVERNAME, that you SQL Server installation uses the instance name INSTANCE_NAME, and that windows auth is the default auth method. After execution output.txt will contain something like the following:
...
(1 rows affected)
Processed 100 total records
(1 rows affected)
Processed 200 total records
(1 rows affected)
Processed 300 total records
...
use readfileonline.com if you need to see the contents of huge files.
UPDATE
This link provides more command line options and details such as username and password:
https://dba.stackexchange.com/questions/44101/importing-sql-server-database-from-a-sql-file
My guess is that you've got something in method1
which wraps one exception in another, and uses the toString()
of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage()
behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message
This query should work very well on MySQL:
SELECT concat(left(curdate(),7),'-01')
Assuming this is a personal certificate created by windows on the system you copied your project from, you can use the certificate manager on the system where the project is now and import the certificate. Start the certificate manager (certmgr) and select the personal certificates then right click below the list of existing certificates and select import from the tasks. Use the browse to find the .pfx in the project (the .pfx from the previous system that you copied over with the project). It should be in the sub-directory with the same name as the project directory. I am familiar with C# and VS, so if that is not your environment maybe the .pfx will be elsewhere or maybe this suggestion does not apply. After the import you should get a status message. If you succeeded, the compile certificate error should be gone.
You can create a timeoutPromise wrapper
function timeoutPromise(timeout, err, promise) {
return new Promise(function(resolve,reject) {
promise.then(resolve,reject);
setTimeout(reject.bind(null,err), timeout);
});
}
You can then wrap any promise
timeoutPromise(100, new Error('Timed Out!'), fetch(...))
.then(...)
.catch(...)
It won't actually cancel an underlying connection but will allow you to timeout a promise.
Reference
From the doc for path.resolve
:
The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.
But path.join
keeps trailing slashes
So
__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'
Sending a json object from Android is easy if you use Apache HTTP Client. Here's a code sample on how to do it. You should create a new thread for network activities so as not to lock up the UI thread.
protected void sendJson(final String email, final String pwd) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(URL);
json.put("email", email);
json.put("password", pwd);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch(Exception e) {
e.printStackTrace();
createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
You could also use Google Gson to send and retrieve JSON.
Updated answer for how to find which version of Swift your project is using in a few click in Xcode 12 to help out rookies like me.
I had the same problem even when I created a fresh project.
I was creating the Java project within Eclipse, then mavenize it, then going into java build path properties removing src/
and adding src/main/java
and src/test/java
. When I run Maven update it used to give nested path error.
Then I finally realized -because I had not seen that entry before- there is a <sourceDirectory>src</sourceDirectory>
line in pom file written when I mavenize it. It was resolved after removing it.
Try to change the loop like this:
for line in $(cat filename); do
read input
echo $input;
done
Unit test:
for line in $(cat /etc/passwd); do
read input
echo $input;
echo "[$line]"
done
<script>
$(function(){
$('.movie').click(function(){
var this_href=$(this).attr('href');
$.ajax({
url:this_href,
type:'post',
cache:false,
success:function(data)
{
$('#summary').html(data);
}
});
return false;
});
});
</script>
Open xcode and in the top menu go to xcode > Preferences > Downloads and you will be given the option to download old sdks to use with xcode. You can also download command line tools and Device Debugging Support.
By using document.getElementById()
function you don't have to pass #
before element's id.
Code:
document.getElementById('_1234').checked = true;
Demo: JSFiddle
Rachel's solution is working fine, although you need to use the third party script from raw.githubusercontent.com
By now there is a feature they show on the landing page when advertisng the "modular" script. You can see a legend there with this structure:
<div class="labeled-chart-container">
<div class="canvas-holder">
<canvas id="modular-doughnut" width="250" height="250" style="width: 250px; height: 250px;"></canvas>
</div>
<ul class="doughnut-legend">
<li><span style="background-color:#5B90BF"></span>Core</li>
<li><span style="background-color:#96b5b4"></span>Bar</li>
<li><span style="background-color:#a3be8c"></span>Doughnut</li>
<li><span style="background-color:#ab7967"></span>Radar</li>
<li><span style="background-color:#d08770"></span>Line</li>
<li><span style="background-color:#b48ead"></span>Polar Area</li>
</ul>
</div>
To achieve this they use the chart configuration option legendTemplate
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
You can find the doumentation here on chartjs.org This works for all the charts although it is not part of the global chart configuration.
Then they create the legend and add it to the DOM like this:
var legend = myPie.generateLegend();
$("#legend").html(legend);
Sample See also my JSFiddle sample
This solution is no more supported since jQuery 1.8 as we can read on the blog here:
$(element).data(“events”): This is now removed in 1.8, but you can still get to the events data for debugging purposes via $._data(element, "events"). Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.
So, you should unbind/rebind it or simply, use a boolean to determine if your event as been attached or not (which is in my opinion the best solution).
The following signature will do:
List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);
Spring Data JPA supports a large number of keywords to build a query. IN
and AND
are among them.
The answer is simple: people say ruby is slow because it is slow based on measured comparisons to other languages. Bear in mind, though, "slow" is relative. Often, ruby and other "slow" languages are plenty fast enough.
You could do:
sub("*\\.[0-9]", "", a)
or
library(stringr)
str_sub(a, start=1, end=-3)
Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):
byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();
list_of_tuples = [('1', '2', '3', '4'),
('2', '3', '4', '5'),
('3', '4', '5', '6'),
('4', '5', '6', '7')]
def mod_tuples(list_of_tuples):
for i in range(0, len(list_of_tuples)):
addition = ''
for x in list_of_tuples[i]:
addition = addition + x
list_of_tuples[i] = list_of_tuples[i] + (addition,)
return list_of_tuples
# check:
print mod_tuples(list_of_tuples)
I use the following to dynamically adjust height of the select2 dropdown element so it nicely fits the amount of options:
$('select').on('select2:open', function (e) {
var OptionsSize = $(this).find("option").size(); // The amount of options
var HeightPerOption = 36; // the height in pixels every option should be
var DropDownHeight = OptionsSize * HeightPerOption;
$(".select2-results__options").height(DropDownHeight);
});
Make sure to unset the (default) max-height in css:
.select2-container--default .select2-results>.select2-results__options {
max-height: inherit;
}
(only tested in version 4 of select2)
Server Error 500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed. Goddady. Hosting - Web - Economy - Windows Plesk
In my case, I replace this code:
<configuration>
<system.webServer>
<httpErrors errorMode="Detailed" />
<asp scriptErrorSentToBrowser="true"/>
</system.webServer>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>
Then change framework 3.5 to framework 4. It shows my detailed error. I delete code in:
<httpModules></httpModules>
It solved my problem.
You can use ROW_NUMBER(). You can specify where conditions as well. (e.g. Name LIKE'MyName%
in the following query)
SELECT *
FROM (SELECT ID, Name, Email,
ROW_NUMBER() OVER (PARTITION BY Email ORDER BY ID) AS RowNumber
FROM MyTable
WHERE Name LIKE 'MyName%') AS a
WHERE a.RowNumber = 1
Try this for readability and best practices:
Python2
import types
if isinstance(lst, types.ListType) or isinstance(lst, types.TupleType):
# Do something
Python3
import typing
if isinstance(lst, typing.List) or isinstance(lst, typing.Tuple):
# Do something
Hope it helps.
In Weblogic 9.2 the configuration via console is as follows:
I believe the default value was 60
.
Remember to use Release Configuration
button after you edit the field.
This answer is as much for my future self as for anyone else. I have encountered this exact problem when I am logged in correctly, but I am attempting to push to a private repo when my number of private repos is greater than or equal to the limit allowed by my plan.
I'm not exactly sure how I was able to create too many private repos, but if my plan includes 5 private repos, and somehow I have 6, then this is the error that I will receive:
denied: requested access to the resource is denied
In my case it's possible that I ended up with too many private repositories because I have my default visibility set to private:
This is where you determine how many private repos you can have:
Once I made the problematic repo public, the issue became apparent:
NB: Using jQuery 3.4.1
$.ajax({
url: URL,
success: function(data, textStatus, jqXHR){
console.log(textStatus + ": " + jqXHR.status);
// do something with data
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus + ": " + jqXHR.status + " " + errorThrown);
}
});
you will need to button initilzation inside method instead of trying to initlzing View's at class level do it as:
Button button; //<< declare here..
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.standingsButton); //<< initialize here
// set OnClickListener for Button here
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,StandingsActivity.class));
}
});
}
git remote add origin <remote_repo_url>
git push --all origin
If you want to set all of your branches to automatically use this remote repo when you use git pull
, add --set-upstream
to the push:
git push --all --set-upstream origin
for 32 characters:
for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)
I set cookies in React using the react-cookie library, it has options you can pass in options to set expiration time.
Check it out here
An example of its use for your case:
import cookie from "react-cookie";
setCookie() => {
let d = new Date();
d.setTime(d.getTime() + (minutes*60*1000));
cookie.set("onboarded", true, {path: "/", expires: d});
};
Easy CSS properties can do the trick. The following is for a three-line ellipsis.
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
dynamic version
ALTER PROCEDURE [dbo].[ReseedTableIdentityCol](@p_table varchar(max))-- RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE @sqlCommand nvarchar(1000)
DECLARE @maxVal INT
set @sqlCommand = 'SELECT @maxVal = ISNULL(max(ID),0)+1 from '+@p_table
EXECUTE sp_executesql @sqlCommand, N'@maxVal int OUTPUT',@maxVal=@maxVal OUTPUT
DBCC CHECKIDENT(@p_table, RESEED, @maxVal)
END
exec dbo.ReseedTableIdentityCol @p_table='Junk'
See my comment. You need to include the full org.json library when running as android.jar only contains stubs to compile against.
In addition, you must remove the two instances of extra }
in your JSON data following longitude
.
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
Apart from that, geodata
is in fact not a JSONObject
but a JSONArray
.
Here is the fully working and tested corrected code:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ShowActivity {
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
public static void main(final String[] argv) throws JSONException {
final JSONObject obj = new JSONObject(JSON_DATA);
final JSONArray geodata = obj.getJSONArray("geodata");
final int n = geodata.length();
for (int i = 0; i < n; ++i) {
final JSONObject person = geodata.getJSONObject(i);
System.out.println(person.getInt("id"));
System.out.println(person.getString("name"));
System.out.println(person.getString("gender"));
System.out.println(person.getDouble("latitude"));
System.out.println(person.getDouble("longitude"));
}
}
}
Here's the output:
C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985
The easiest way I found to set Facebook Open Graph to every Joomla article, was to place in com_content/article/default.php override, next code:
$app = JFactory::getApplication();
$path = JURI::root();
$document = JFactory::getDocument();
$document->addCustomTag('<meta property="og:title" content="YOUR SITE TITLE" />');
$document->addCustomTag('<meta property="og:name" content="YOUR SITE NAME" />');
$document->addCustomTag('<meta property="og:description" content="YOUR SITE DESCRIPTION" />');
$document->addCustomTag('<meta property="og:site_name" content="YOUR SITE NAME" />');
if (isset($images->image_fulltext) and !empty($images->image_fulltext)) :
$document->addCustomTag('<meta property="og:image" content="'.$path.'<?php echo htmlspecialchars($images->image_fulltext); ?>" />');
else :
$document->addCustomTag('<meta property="og:image" content="'.$path.'images/logo.png" />');
endif;
This will place meta og tags in the head with details from current article.
I think you should store the size somewhere.
The null-terminated-string kind of model for determining array length is a bad idea. For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise.
Having that said, a good solution might be glib's Arrays, they have the added advantage of expanding automatically if you need to add more items.
P.S. to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library.
Based on Jayarjo's answer:
var loopDate = new Date();
loopDate.setTime(datFrom.valueOf());
while (loopDate.valueOf() < datTo.valueOf() + 86400000) {
alert(loopDay);
loopDate.setTime(loopDate.valueOf() + 86400000);
}
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
I needed to snapshot a div on the page (for a webapp I wrote) that is protected by JWT's and makes very heavy use of Angular.
I had no luck with any of the above methods.
I ended up taking the outerHTML of the div I needed, cleaning it up a little (*) and then sending it to the server where I run wkhtmltopdf against it.
This is working very well for me.
(*) various input devices in my pages didn't render as checked or have their text values when viewed in the pdf... So I run a little bit of jQuery on the html before I send it up for rendering. ex: for text input items -- I copy their .val()'s into 'value' attributes, which then can be seen by wkhtmlpdf
const inpT = document.getElementById("text-box");_x000D_
const inpC = document.getElementById("text-box-content");_x000D_
// swch gets inputs ._x000D_
var swch;_x000D_
// swch if corsur is active in inputs defaulte is false ._x000D_
var isSelect = false;_x000D_
_x000D_
var crnselect;_x000D_
// on focus_x000D_
function setSwitch(e) {_x000D_
swch = e;_x000D_
isSelect = true;_x000D_
console.log("set Switch: " + isSelect);_x000D_
}_x000D_
// on click ev_x000D_
function setEmoji() {_x000D_
if (isSelect) {_x000D_
console.log("emoji added :)");_x000D_
swch.value += ":)";_x000D_
swch.setSelectionRange(2,2 );_x000D_
isSelect = true;_x000D_
}_x000D_
_x000D_
}_x000D_
// on not selected on input . _x000D_
function onout() {_x000D_
// ?????? ??? ?? ?? _x000D_
crnselect = inpC.selectionStart;_x000D_
_x000D_
// return input select not active after 200 ms ._x000D_
var len = swch.value.length;_x000D_
setTimeout(() => {_x000D_
(len == swch.value.length)? isSelect = false:isSelect = true;_x000D_
}, 200);_x000D_
}
_x000D_
<h1> Try it !</h1>_x000D_
_x000D_
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">_x000D_
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box-content" size="20" value="content">_x000D_
<button onclick="setEmoji()">emogi :) </button>
_x000D_
Try adding a button on mdi parent and add this code' to set your mdi child inside the mdi parent. change the yourchildformname to your MDI Child's form name and see if this works.
Dim NewMDIChild As New yourchildformname()
'Set the Parent Form of the Child window.
NewMDIChild.MdiParent = Me
'Display the new form.
NewMDIChild.Show()
The @ianhanniballake's answer is absolutely correct and simple. But it took me few days to understand. For someone who don't understand his answer, here is more detail implementation
<Button
android:id="@+id/btn"
style="@style/MaterialButton"
... />
<style name="MaterialButton" parent="Widget.AppCompat.Button.Colored">
<item name="android:theme">@style/Theme.MaterialButton</item>
...
</style>
<style name="Theme.MaterialButton" parent="YourTheme">
<item name="colorAccent">@color/yourAccentColor</item>
<item name="colorButtonNormal">@color/yourButtonNormalColor</item>
</style>
===Or===
<Button
android:id="@+id/btn"
style="@style/Widget.AppCompat.Button.Colored"
android:theme="@style/Theme.MaterialButton" />
<style name="Theme.MaterialButton" parent="YourTheme">
<item name="colorAccent">@color/yourAccentColor</item>
<item name="colorButtonNormal">@color/yourButtonNormalColor</item>
</style>
You don't need to give local path. just give cdn link of bootstrap datetimepicker. and it works.
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class='col-sm-6'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<script type="text/javascript">_x000D_
$(function () {_x000D_
$('#datetimepicker').datepicker();_x000D_
});_x000D_
</script>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
To attach the Java source code with Eclipse,
When you install the JDK, you must have selected the option to install the Java source files too. This will copy the src.zip file in the installation directory. In Eclipse, go to Window -> Preferences -> Java -> Installed JREs -> Add and choose the JDK you have in your system. Eclipse will now list the JARs found in the dialog box. There, select the rt.jar and choose Source Attachment. By default, this will be pointing to the correct src.zip. If not, choose the src.zip file which you have in your java installation directory. java source attach in eclipse Similarly, if you have the javadoc downloaded in your machine, you can configure that too in this dialog box.
Instructions as of Dec 2018:
Now when you open the shortcut it will open in a window without toolbar.
On Windows 10 with Python 3.9.1, using the command line:
py -V
Python 3.9.1
py --version
Python 3.9.1
You can also use Json.NET.
return JsonConvert.SerializeObject(jsonResult.Data);
As json.loads
simply returns a dict, you can use the operators that apply to dicts:
>>> jdata = json.load('{"uri": "http:", "foo", "bar"}')
>>> 'uri' in jdata # Check if 'uri' is in jdata's keys
True
>>> jdata['uri'] # Will return the value belonging to the key 'uri'
u'http:'
Edit: to give an idea regarding how to loop through the data, consider the following example:
>>> import json
>>> jdata = json.loads(open ('bookmarks.json').read())
>>> for c in jdata['children'][0]['children']:
... print 'Title: {}, URI: {}'.format(c.get('title', 'No title'),
c.get('uri', 'No uri'))
...
Title: Recently Bookmarked, URI: place:folder=BOOKMARKS_MENU(...)
Title: Recent Tags, URI: place:sort=14&type=6&maxResults=10&queryType=1
Title: , URI: No uri
Title: Mozilla Firefox, URI: No uri
Inspecting the jdata
data structure will allow you to navigate it as you wish. The pprint
call you already have is a good starting point for this.
Edit2: Another attempt. This gets the file you mentioned in a list of dictionaries. With this, I think you should be able to adapt it to your needs.
>>> def build_structure(data, d=[]):
... if 'children' in data:
... for c in data['children']:
... d.append({'title': c.get('title', 'No title'),
... 'uri': c.get('uri', None)})
... build_structure(c, d)
... return d
...
>>> pprint.pprint(build_structure(jdata))
[{'title': u'Bookmarks Menu', 'uri': None},
{'title': u'Recently Bookmarked',
'uri': u'place:folder=BOOKMARKS_MENU&folder=UNFILED_BOOKMARKS&(...)'},
{'title': u'Recent Tags',
'uri': u'place:sort=14&type=6&maxResults=10&queryType=1'},
{'title': u'', 'uri': None},
{'title': u'Mozilla Firefox', 'uri': None},
{'title': u'Help and Tutorials',
'uri': u'http://www.mozilla.com/en-US/firefox/help/'},
(...)
}]
To then "search through it for u'uri': u'http:'
", do something like this:
for c in build_structure(jdata):
if c['uri'].startswith('http:'):
print 'Started with http'
myClub.distance = Console.ReadLine();
should be
myClub.mydistance = Console.ReadLine();
use your public properties that you have defined for others as well instead of the protected field members.
git reset --hard 1258f0d0aae
But be careful, if the descendant commits between 1258f0d0aae
and HEAD
are not referenced in other branches it'll be tedious (but not impossible) to recover them, so you'd better to create a "backup" branch at current HEAD
, checkout master
, and reset to the commit you want.
Also, be sure that you don't have uncommitted changes before a reset --hard
, they will be truly lost (no way to recover).
in python the operators should be in quotes: db.ProductData.update({'fromAddress':'http://localhost:7000/'}, {"$set": {'fromAddress': 'http://localhost:5000/'}},{"multi": True})
In addition to the above mentioned answers: I wanted to start a job with a simple parameter passed to a second pipeline and found the answer on http://web.archive.org/web/20160209062101/https://dzone.com/refcardz/continuous-delivery-with-jenkins-workflow
So i used:
stage ('Starting ART job') {
build job: 'RunArtInTest', parameters: [[$class: 'StringParameterValue', name: 'systemname', value: systemname]]
}