In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
Look at java.lang.BigDecimal, may solve your problem.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
Clean Project -> Invalidate caches/restart. My problem resolved with this.
I upgraded my IntelliJ Version from 2018.1 to 2018.3.6. It works !
I solved it by deleting "/.idea/libraries" from project. Thanks
If you use webpack devServer the simplest way is to set disableHostCheck, check webpack doc like this
devServer: {
contentBase: path.join(__dirname, './dist'),
compress: true,
host: 'localhost',
// host: '0.0.0.0',
port: 8080,
disableHostCheck: true //for ngrok
},
I hit this exact same error and was Googling all over trying to find what I'm doing wrong as that is generated build values-26 code and not styles that I provided. I tried everything from Gradle 4.0 to Android Studio preview 3.0 to canary channel, you name it.
I never found the answer online. In the end, I was able to go back to standard Dev Android Studio and 2.3.3 Gradle as I ended up accidentally fixing it :).
Turned out I was so focused on updating my library project that I was not noticing that the error was caused from an unused sub module (demo app) that is nested in my library project. Once I updated the sub module to match the 26 build tools and 26+ design and support libraries my problem went away.
Not sure if that is what you are seeing as well, but personally I was only updating the lib to release again so wasn't caring about the sample app module, and the error sure appeared to be related to 26 sdk which I only touched in the lib module so wasn't thinking to check the other one. So that was the problem all along for me. Hopefully that fixes you as well. I had this error in 2 library projects and it fixed it in both.
Goodluck either way and if this doesn't resolve your issue, please share what did. BTW 26.0.01 build tools and 26.1.0 design and support is where I ended up going to in the end, although 26.0.1 worked fine as well.
When I used the Scaffold-DbContext command, it didn't include the "[key]" annotation in the model files or the "entity.HasKey(..)" entry in the "modelBuilder.Entity" blocks. My solution was to add a line like this in every "modelBuilder.Entity" block in the *Context.cs file:
entity.HasKey(X => x.Id);
I'm not saying this is better, or even the right way. I'm just saying that it worked for me.
I upgraded VS2017 from version 15.2 to 15.8. With version 15.8 here's what happened:
Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0 no longer worked for me! I had to change it to 10.0.17134.0 and then everything built again. After the upgrade and without making this change, I was getting the same header file errors.
I would have submitted this as a comment on one of the other answers but I don't have enough reputation yet.
Because async/await uses promises under the hood, you can write a little utility function like this:
export function catchEm(promise) {
return promise.then(data => [null, data])
.catch(err => [err]);
}
Then import it whenever you need to catch some errors, and wrap your async function which returns a promise with it.
import catchEm from 'utility';
async performAsyncWork() {
const [err, data] = await catchEm(asyncFunction(arg1, arg2));
if (err) {
// handle errors
} else {
// use data
}
}
I have faced same issue, it may be issue of administrator, so followed below steps to setup docker on
windows10
.
Docker Desktop Installer.exe
file will be downloaded.Docker Desktop Installer.exe
using Run as administrator
-> Mark windows container during installation else it will only install linux container. It will ask for Logout after logging out and login it shows docker desktop in menu.Run as administrator
For MIUI OS Device
1) Go to Setting
2) Scroll down to Additional Setting
3) You will find Developer option at bottom
4) Turn this on - Install via USB: Toggle On
By turning this on, It is working charm in my MIUI8 device.
You are facing issue in
s1.name="Paolo";
because, in the LHS, you're using an array type, which is not assignable.
To elaborate, from C11
, chapter §6.5.16
assignment operator shall have a modifiable lvalue as its left operand.
and, regarding the modifiable lvalue, from chapter §6.3.2.1
A modifiable lvalue is an lvalue that does not have array type, [...]
You need to use strcpy()
to copy into the array.
That said, data s1 = {"Paolo", "Rossi", 19};
works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9
Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]
As I am new, I can't comment on other answers.
If someone is looking for an answer to make this work (and can use javascript - as it seems to be required to make this work at the moment) this approach has worked pretty well for me and it accounts for mobile orientation change as well. I use Jquery for the example code but should be doable with vanillaJS.
-First, I use a script to detect if the device is touch or hover. Bare-bones example:
if ("ontouchstart" in document.documentElement) {
document.body.classList.add('touch-device');
} else {
document.body.classList.add('hover-device');
}
This adds class to the body element according to the device type (hover or touch) that can be used later for the height script.
-Next use this code to set height of the device on load and on orientation change:
if (jQuery('body').hasClass("touch-device")) {
//Loading height on touch-device
function calcFullHeight() {
jQuery('.hero-section').css("height", $(window).height());
}
(function($) {
calcFullHeight();
jQuery(window).on('orientationchange', function() {
// 500ms timeout for getting the correct height after orientation change
setTimeout(function() {
calcFullHeight();
}, 500);
});
})(jQuery);
} else {
jQuery('.hero-section').css("height", "100vh");
}
-Timeout is set so that the device would calculate the new height correctly on orientation change. If there is no timeout, in my experience the height will not be correct. 500ms might be an overdo but has worked for me.
-100vh on hover-devices is a fallback if the browser overrides the CSS 100vh.
Go to Phone Settings --> Developer Options --> Simulate Secondary Displays
and turn it to None
.
If you don't see Developer Options
in the settings menu
(it should be at the bottom, go Settings ==> About phone
and tap on the Build number
a lot of times)
You may not place the deprecated non-block-scoped stage
(as in the original question) inside parallel
.
As of JENKINS-26107, stage
takes a block argument. You may put parallel
inside stage
or stage
inside parallel
or stage
inside stage
etc. However visualizations of the build are not guaranteed to support all nestings; in particular
stage
nesting.parallel
branches inside a top-level stage, but currently no more.JENKINS-27394, if implemented, would display arbitrarily nested stage
s.
I had exact issue and here is how I fixed:
I found out that I had first installed Keras then installed pandas in my virtual env. When you install keras, pandas is shipped with it. Do not need to pip install pandas.
I tested this hypothesis by creating new virtual environment and wala... pandas appeared without me installing it. Thus I came to the conclusion that pandas is automatically installed when you pip install keras.
update 2 ::slotted
::slotted
is now supported by all new browsers and can be used with ViewEncapsulation.ShadowDom
https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted
update 1 ::ng-deep
/deep/
was deprecated and replaced by ::ng-deep
.
::ng-deep
is also already marked deprecated, but there is no replacement available yet.
When ViewEncapsulation.Native
is properly supported by all browsers and supports styling accross shadow DOM boundaries, ::ng-deep
will probably be discontinued.
original
Angular adds all kinds of CSS classes to the HTML it adds to the DOM to emulate shadow DOM CSS encapsulation to prevent styles of bleeding in and out of components. Angular also rewrites the CSS you add to match these added classes. For HTML added using [innerHTML]
these classes are not added and the rewritten CSS doesn't match.
As a workaround try
/* :host /deep/ mySelector { */
:host ::ng-deep mySelector {
background-color: blue;
}
index.html
/* body /deep/ mySelector { */
body ::ng-deep mySelector {
background-color: green;
}
>>>
(and the equivalent/deep/
but /deep/
works better with SASS) and ::shadow
were added in 2.0.0-beta.10. They are similar to the shadow DOM CSS combinators (which are deprecated) and only work with encapsulation: ViewEncapsulation.Emulated
which is the default in Angular2. They probably also work with ViewEncapsulation.None
but are then only ignored because they are not necessary.
These combinators are only an intermediate solution until more advanced features for cross-component styling is supported.
Another approach is to use
@Component({
...
encapsulation: ViewEncapsulation.None,
})
for all components that block your CSS (depends on where you add the CSS and where the HTML is that you want to style - might be all components in your application)
Update
To align some elements (headerElement) in the center and the last element to the right (headerEnd).
.headerElement {
margin-right: 5%;
margin-left: 5%;
}
.headerEnd{
margin-left: auto;
}
Creator of the change-case extension here. I've updated the extension to support spanning lines.
To map the upper case command to a keybinding (e.g. CTRL+T+U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:
{
"key": "ctrl+t ctrl+u",
"command": "extension.changeCase.upper",
"when": "editorTextFocus"
}
EDIT:
With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase
and editor.action.transformToLowercase
. These don't have default keybindings. They also work with multi-line blocks.
The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake_case, kebab-case, etc.
As far as the themes, VS Code is every bit as editable as Sublime. You can edit any of the default themes that come with VS code. You just have to know where to find the theme files.
Side note: I love the Monokai theme. However, all I wanted to change about it was the background. I don't like the dark grayish background. Instead, I think the contrast is WAY better with a solid black background. The code pops out much more.
Anyways, I hunted for the theme file and found it (in windows) at:
c:\Program Files (x86)\Microsoft VS Code\resources\app\extensions\theme-monokai\themes\
In that folder I found the Monokai.tmTheme file and modified the first background key as follows:
<key>background</key>
<string>#000000</string>
There are a few 'background' key in the theme file, make sure you edit the correct one. The one I edited was at the very top. Line 12 I think.
To replace the old version with the new one, you need to change the link for it. Type that command to terminal.
brew link --force openssl
Check the version of openssl again. It should be changed.
Actually, there's more than one issue here. The main one is that xargs
by default executes the command you specified, even when no arguments have been passed. To change that you might use a GNU extension to xargs
:
--no-run-if-empty
-r
If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension.
Simple example:
find . -mmin -60 | xargs -r ls -l
But this might match to all subdirectories, including .
(the current directory), and ls
will list each of them individually. So the output will be a mess. Solution: pass -d
to ls
, which prohibits listing the directory contents:
find . -mmin -60 | xargs -r ls -ld
Now you don't like .
(the current directory) in your list? Solution: exclude the first directory level (0
) from find output:
find . -mindepth 1 -mmin -60 | xargs -r ls -ld
Now you'd need only the files in your list? Solution: exclude the directories:
find . -type f -mmin -60 | xargs -r ls -l
Now you have some files with names containing white space, quote marks, or backslashes? Solution: use null-terminated output (find) and input (xargs) (these are also GNU extensions, afaik):
find . -type f -mmin -60 -print0 | xargs -r0 ls -l
On an belgium keyboard asserted on the mac command + shift + / is the keystroke for commenting out a block.
Another thing to add, in the version I'm using, the code has to be initialized in order to be to comment it out using CTRL and / . If you haven't ran the code and the code isn't colorized it wont work.
You should define the function textcolor before. Because textcolor is not a standard function in C.
void textcolor(unsigned short color) {
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hcon,color);
}
I would definitely use html markers to achieve this. Just surround your text with <p></p>
or <font></font>
and add the desired attributes. See the following example:
<p style="font-family: times, serif; font-size:11pt; font-style:italic">
Why did we use these specific parameters during the calculation of the fingerprints?
</p>
This will produce the following output
compared to
This would work with Jupyter Notebook as well as Typora, but I'm not sure if it is universal.
Lastly, be aware that the html marker overrides the font styling used by Markdown.
There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.
I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.
From the netstat
output you can see the process is listening on address 127.0.0.1
tcp 0 0 127.0.0.1:9000 0.0.0.0:* ...
from the exception message you can see that it tries to connect to address 127.0.1.1
java.net.ConnectException: Call From marta-komputer/127.0.1.1 to localhost:9000 failed ...
further in the exception it's mentionend
For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
on this page you find
Check that there isn't an entry for your hostname mapped to 127.0.0.1 or 127.0.1.1 in /etc/hosts (Ubuntu is notorious for this)
so the conclusion is to remove this line in your /etc/hosts
127.0.1.1 marta-komputer
I figured out that the plt.pause(0.001)
command is the only thing needed and nothing else.
plt.show() and plt.draw() are unnecessary and / or blocking in one way or the other. So here is a code that draws and updates a figure and keeps going. Essentially plt.pause(0.001) seems to be the closest equivalent to matlab's drawnow.
Unfortunately those plots will not be interactive (they freeze), except you insert an input() command, but then the code will stop.
The documentation of the plt.pause(interval) command states:
If there is an active figure, it will be updated and displayed before the pause...... This can be used for crude animation.
and this is pretty much exactly what we want. Try this code:
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0, 51) # x coordinates
for z in range(10, 50):
y = np.power(x, z/10) # y coordinates of plot for animation
plt.cla() # delete previous plot
plt.axis([-50, 50, 0, 10000]) # set axis limits, to avoid rescaling
plt.plot(x, y) # generate new plot
plt.pause(0.1) # pause 0.1 sec, to force a plot redraw
allow from all
will not work along with Require local
. Instead, try Require ip xxx.xxx.xxx.xx
For Example:
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Require local
Require ip 10.0.0.1
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
I have also met this issue. In my case, the image path is wrong, so the img read is NoneType
. After I correct the image path, I can show it without any issue.
I had a similar issue but I was unable to use the UserAgent
class inside the fake_useragent
module. I was running the code inside a docker container
import requests
import ujson
import random
response = requests.get('https://fake-useragent.herokuapp.com/browsers/0.1.11')
agents_dictionary = ujson.loads(response.text)
random_browser_number = str(random.randint(0, len(agents_dictionary['randomize'])))
random_browser = agents_dictionary['randomize'][random_browser_number]
user_agents_list = agents_dictionary['browsers'][random_browser]
user_agent = user_agents_list[random.randint(0, len(user_agents_list)-1)]
I targeted the endpoint used in the module. This solution still gave me a random user agent however there is the possibility that the data structure at the endpoint could change.
%>%
is similar to pipe in Unix. For example, in
a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()
the output of combined_data_set
will go into group_by
and its output will go into tally
, then the final output is assigned to a
.
This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.
Swift4:
let key = "ccC2H19lDDbQDfakxcrtNMQdd0FloLGG" // length == 32
let iv = "ggGGHUiDD0Qjhuvv" // length == 16
func encryptFile(_ path: URL) -> Bool{
do{
let data = try Data.init(contentsOf: path)
let encodedData = try data.aesEncrypt(key: key, iv: iv)
try encodedData.write(to: path)
return true
}catch{
return false
}
}
func decryptFile(_ path: URL) -> Bool{
do{
let data = try Data.init(contentsOf: path)
let decodedData = try data.aesDecrypt(key: key, iv: iv)
try decodedData.write(to: path)
return true
}catch{
return false
}
}
Install CryptoSwift
import CryptoSwift
extension Data {
func aesEncrypt(key: String, iv: String) throws -> Data{
let encypted = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).encrypt(self.bytes)
return Data(bytes: encypted)
}
func aesDecrypt(key: String, iv: String) throws -> Data {
let decrypted = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).decrypt(self.bytes)
return Data(bytes: decrypted)
}
}
From this excellent article on query locks in Postgres, one can get blocked query and blocker query and their information from the following query.
CREATE VIEW lock_monitor AS(
SELECT
COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item,
now() - blockeda.query_start AS waiting_duration, blockeda.pid AS blocked_pid,
blockeda.query as blocked_query, blockedl.mode as blocked_mode,
blockinga.pid AS blocking_pid, blockinga.query as blocking_query,
blockingl.mode as blocking_mode
FROM pg_catalog.pg_locks blockedl
JOIN pg_stat_activity blockeda ON blockedl.pid = blockeda.pid
JOIN pg_catalog.pg_locks blockingl ON(
( (blockingl.transactionid=blockedl.transactionid) OR
(blockingl.relation=blockedl.relation AND blockingl.locktype=blockedl.locktype)
) AND blockedl.pid != blockingl.pid)
JOIN pg_stat_activity blockinga ON blockingl.pid = blockinga.pid
AND blockinga.datid = blockeda.datid
WHERE NOT blockedl.granted
AND blockinga.datname = current_database()
);
SELECT * from lock_monitor;
As the query is long but useful, the article author has created a view for it to simplify it's usage.
If you are using macOS, add both Android SDK emulator
and tools
directories to the path:
Step 1: In my case the order was important, first emulator
and then tools
.
export ANDROID_SDK=$HOME/Library/Android/sdk
export PATH=$ANDROID_SDK/emulator:$ANDROID_SDK/tools:$PATH
Step 2: Reload you .bash_profile
Or .bashrc
depending on OS
Step 3: Get list of emulators available:
$emulator -list-avds
Step 4: Launch emulator from the command line and Replace avd
with the name of your emulator $emulator @avd
Don't forget to add the @
symbol.
This was tested with macOS High Sierra 10.13.4 and Android Studio 3.1.2.
In my case, the app crashed because I didn't set the storyboard's target membership.
After a bit of trial and error... as mentioned in the possible answers, it turned out to require xfs_growfs
rather than resize2fs
.
CentOS 7,
fdisk /dev/xvda
Create new primary partition, set type as linux lvm
.
n
p
3
t
8e
w
Create a new primary volume and extend the volume group to the new volume.
partprobe
pvcreate /dev/xvda3
vgextend /dev/centos /dev/xvda3
Check the physical volume for free space, extend the logical volume with the free space.
vgdisplay -v
lvextend -l+288 /dev/centos/root
Finally perform an online resize to resize the logical volume, then check the available space.
xfs_growfs /dev/centos/root
df -h
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
I have been researching this for a while, tested and wrote apps.
If you have no option in Settings ? Phone ? Use proximity sensor
, then the only choice, seem to be to disable or modify its settings in rooted devices.
Also consider, that if you plug the headset, the screen will remain on :D
Regarding the question,
” can someone explain why the
compare()
function exists if a comparison can be made using simple operands?
Relative to <
and ==
, the compare
function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.
As an example of simplicity, for small integer values you can write a compare function like this:
auto compare( int a, int b ) -> int { return a - b; }
which is highly efficient.
Now for a structure
struct Foo
{
int a;
int b;
int c;
};
auto compare( Foo const& x, Foo const& y )
-> int
{
if( int const r = compare( x.a, y.a ) ) { return r; }
if( int const r = compare( x.b, y.b ) ) { return r; }
return compare( x.c, y.c );
}
Trying to express this lexicographic compare directly in terms of <
you wind up with horrendous complexity and inefficiency, relatively speaking.
With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.
In Swift 4 and 5. I created a closure variable containing two parameter dictionary and bool.
var completionHandler:([String:Any], Bool)->Void = { dict, success in
if success {
print(dict)
}
}
Calling the closure variable
self.completionHandler(["name":"Gurjinder singh"],true)
Use Capture list
Defining a Capture List
Each item in a capture list is a pairing of the weak or unowned keyword with a reference to a class instance (such as self) or a variable initialized with some value (such as delegate = self.delegate!). These pairings are written within a pair of square braces, separated by commas.
Place the capture list before a closure’s parameter list and return type if they are provided:
lazy var someClosure: (Int, String) -> String = {
[unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
// closure body goes here
}
If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by the in keyword:
lazy var someClosure: Void -> String = {
[unowned self, weak delegate = self.delegate!] in
// closure body goes here
}
I have found this better way , no need to remove data , just call the source of the remote content each time
$(document).ready(function() {
$('.class').click(function() {
var id = this.id;
//alert(id);checking that have correct id
$("#iframe").attr("src","url?id=" + id);
$('#Modal').modal({
show: true
});
});
});
I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.
In my case, that just fix my progressive increase of similar blocked threads:
ExecutorService::awaitTermination(x, TimeUnit)
and ExecutorService::shutdownNow()
(if necessary) in my finally clause.For information, I've used the following commands to detect thread count & list locked threads:
ps -u javaAppuser -L|wc -l
jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log
jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log
cat threadPrint*.log |grep "pool-"|wc -l
You can do it as simple as this using swift 2:
let alertController = UIAlertController(title: "iOScreator", message:
"Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
self.pressed()
}))
func pressed()
{
print("you pressed")
}
**or**
let alertController = UIAlertController(title: "iOScreator", message:
"Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
print("pressed")
}))
All the answers above are correct i am just showing another way that can be done.
Example code for node.js - async function to sync function:
var deasync = require('deasync');
function syncFunc()
{
var ret = null;
asyncFunc(function(err, result){
ret = {err : err, result : result}
});
while((ret == null))
{
deasync.runLoopOnce();
}
return (ret.err || ret.result);
}
Just open your setting->compiler and click on the reset defaults and it will start work.
If the setTimeout function does not work for you either, then do the following:
//Create an iframe
iframe = $('body').append($('<iframe id="documentToPrint" name="documentToPrint" src="about:blank"/>'));
iframeElement = $('#documentToPrint')[0].contentWindow.document;
//Open the iframe
iframeElement.open();
//Write your content to the iframe
iframeElement.write($("yourContentId").html());
//This is the important bit.
//Wait for the iframe window to load, then print it.
$('#documentToPrint')[0].contentWindow.onload = function () {
$('#print-document')[0].contentWindow.print();
$('#print-document').remove();
};
iframeElement.close();
The problem could occur when $templateCacheProvider is trying to resolve a template in the templateCache or through your project directory that does not exist
Example:
templateUrl: 'views/wrongPathToTemplate'
Should be:
templateUrl: 'views/home.html'
If the extension is already there but you don't see the uuid_generate_v4() function when you do a describe functions \df command then all you need to do is drop the extension and re-add it so that the functions are also added. Here is the issue replication:
db=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
(0 rows)
CREATE EXTENSION "uuid-ossp";
ERROR: extension "uuid-ossp" already exists
DROP EXTENSION "uuid-ossp";
CREATE EXTENSION "uuid-ossp";
db=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+--------------------+------------------+---------------------------+--------
public | uuid_generate_v1 | uuid | | normal
public | uuid_generate_v1mc | uuid | | normal
public | uuid_generate_v3 | uuid | namespace uuid, name text | normal
public | uuid_generate_v4 | uuid | | normal
db=# select uuid_generate_v4();
uuid_generate_v4
--------------------------------------
b19d597c-8f54-41ba-ba73-02299c1adf92
(1 row)
What probably happened is that the extension was originally added to the cluster at some point in the past and then you probably created a new database within that cluster afterward. If that was the case then the new database will only be "aware" of the extension but it will not have the uuid functions added which happens when you add the extension. Therefore you must re-add it.
I think what you are after is Task.Delay. This doesn't block the thread like Sleep does and it means you can do this using a single thread using the async programming model.
async Task PutTaskDelay()
{
await Task.Delay(5000);
}
private async void btnTaskDelay_Click(object sender, EventArgs e)
{
await PutTaskDelay();
MessageBox.Show("I am back");
}
In general, synchronized
methods are used to protect access to resources that are accessed concurrently. When a resource that is being accessed concurrently belongs to each instance of your class, you use a synchronized
instance method; when the resource belongs to all instances (i.e. when it is in a static
variable) then you use a synchronized static
method to access it.
For example, you could make a static
factory method that keeps a "registry" of all objects that it has produced. A natural place for such registry would be a static
collection. If your factory is used from multiple threads, you need to make the factory method synchronized
(or have a synchronized
block inside the method) to protect access to the shared static
collection.
Note that using synchronized
without a specific lock object is generally not the safest choice when you are building a library to be used in code written by others. This is because malicious code could synchronize on your object or a class to block your own methods from executing. To protect your code against this, create a private "lock" object, instance or static, and synchronize on that object instead.
In the Code::Blocks IDE, navigate Settings -> Debugger
In the tree control at the right, select Common -> GDB/CDB debugger -> Common.
Then in the dialog at the left you can enter Executable path and choose Debugger type = GDB or CDB, as well as configuring various other options.
@media queries serve this purpose. Here's an example:
@media only screen and (max-width: 991px) and (min-width: 769px){
/* CSS that should be displayed if width is equal to or less than 991px and larger
than 768px goes here */
}
@media only screen and (max-width: 991px){
/* CSS that should be displayed if width is equal to or less than 991px goes here */
}
You can select proper options from here
android {
lintOptions {
// set to true to turn off analysis progress reporting by lint
quiet true
// if true, stop the gradle build if errors are found
abortOnError false
// if true, only report errors
ignoreWarnings true
// if true, emit full/absolute paths to files with errors (true by default)
//absolutePaths true
// if true, check all issues, including those that are off by default
checkAllWarnings true
// if true, treat all warnings as errors
warningsAsErrors true
// turn off checking the given issue id's
disable 'TypographyFractions','TypographyQuotes'
// turn on the given issue id's
enable 'RtlHardcoded','RtlCompat', 'RtlEnabled'
// check *only* the given issue id's
check 'NewApi', 'InlinedApi'
// if true, don't include source code lines in the error output
noLines true
// if true, show all locations for an error, do not truncate lists, etc.
showAll true
// Fallback lint configuration (default severities, etc.)
lintConfig file("default-lint.xml")
// if true, generate a text report of issues (false by default)
textReport true
// location to write the output; can be a file or 'stdout'
textOutput 'stdout'
// if true, generate an XML report for use by for example Jenkins
xmlReport false
// file to write report to (if not specified, defaults to lint-results.xml)
xmlOutput file("lint-report.xml")
// if true, generate an HTML report (with issue explanations, sourcecode, etc)
htmlReport true
// optional path to report (default will be lint-results.html in the builddir)
htmlOutput file("lint-report.html")
// set to true to have all release builds run lint on issues with severity=fatal
// and abort the build (controlled by abortOnError above) if fatal issues are found
checkReleaseBuilds true
// Set the severity of the given issues to fatal (which means they will be
// checked during release builds (even if the lint target is not included)
fatal 'NewApi', 'InlineApi'
// Set the severity of the given issues to error
error 'Wakelock', 'TextViewEdits'
// Set the severity of the given issues to warning
warning 'ResourceAsColor'
// Set the severity of the given issues to ignore (same as disabling the check)
ignore 'TypographyQuotes'
}
}
If you want to use Codeblocks and Graphics.h,you can use Codeblocks-EP(I used it when I was learning C in college) then you can try
Codeblocks-EP http://codeblocks.codecutter.org/
In Codeblocks-EP , [File]->[New]->[Project]->[WinBGIm Project]
It has templates for WinBGIm projects installed and all the necessary libraries pre-installed.
OR try this https://stackoverflow.com/a/20321173/5227589
It may be a permission issue,
Please try the following command /etc/init.d/mysqld start
as root user.
You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.
There are two main types of memory you seem to be confusing - stack memory and heap memory.
Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main
, it sets aside some memory for your variables you've declared (p
,token
, and so on).
Heap memory lives from when you malloc
it to when you free
it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!
You have a few errors:
You're trying to free memory that's not heap memory. Don't do that.
You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc
. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.
For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).
EDIT: The malloc function does allocate heap memory*.
"9.9.1 The malloc and free Functions
The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."
~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011
EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.
You should logged in not as "root" user.
Or assign permission to your "current_user" to do this by using following command
sudo chown -R username.www-data /var/www
sudo chmod -R +rwx /var/www
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
As Leo points out, the code you added to your question would not suggest a strong reference cycle (a.k.a., retain cycle). One operation-related issue that could cause a strong reference cycle would be if the operation is not getting released. While your code snippet suggests that you have not defined your operation to be concurrent, but if you have, it wouldn't be released if you never posted isFinished
, or if you had circular dependencies, or something like that. And if the operation isn't released, the view controller wouldn't be released either. I would suggest adding a breakpoint or NSLog
in your operation's dealloc
method and confirm that's getting called.
You said:
I understand the notion of retain cycles, but I am not quite sure what happens in blocks, so that confuses me a little bit
The retain cycle (strong reference cycle) issues that occur with blocks are just like the retain cycle issues you're familiar with. A block will maintain strong references to any objects that appear within the block, and it will not release those strong references until the block itself is released. Thus, if block references self
, or even just references an instance variable of self
, that will maintain strong reference to self, that is not resolved until the block is released (or in this case, until the NSOperation
subclass is released.
For more information, see the Avoid Strong Reference Cycles when Capturing self section of the Programming with Objective-C: Working with Blocks document.
If your view controller is still not getting released, you simply have to identify where the unresolved strong reference resides (assuming you confirmed the NSOperation
is getting deallocated). A common example is the use of a repeating NSTimer
. Or some custom delegate
or other object that is erroneously maintaining a strong
reference. You can often use Instruments to track down where objects are getting their strong references, e.g.:
Or in Xcode 5:
Well I know this answer is not an experienced programmer's approach and of an Old It consultant , but it worked for me .
the answer is "TRY TURNING IT ON AND OFF" . restart codeblocks and it works well reminds me of the 2006 comedy show It Crowd .
I encountered the same problem, probably when I uninstalled it and tried to install it again.
This happens because of the database file containing login details is still stored in the pc, and the new password will not match the older one.
So you can solve this by just uninstalling mysql, and then removing the left over folder from the C:
drive (or wherever you must have installed).
Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain
to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.
See the docs: https://getbootstrap.com/docs/4.0/utilities/display/
In order to hide the content on mobile and display on the bigger devices you have to use the following classes:
d-none d-sm-block
The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.
I suggest to read about that before migration:
https://getbootstrap.com/docs/4.0/migration/#responsive-utilities
Try this:
sudo dpkg-reconfigure mysql-server-{version_number}
version_number
should be mysql version number. For example
sudo dpkg-reconfigure mysql-server-5.6
Then access mysql like this:
mysql -u root -p
By default, Visual Studio searches for headers in the folder where your project is ($ProjectDir) and in the default standard libraries directories. If you need to include something that is not placed in your project directory, you need to add the path to the folder to include:
Go to your Project properties (Project -> Properties -> Configuration Properties -> C/C++ -> General) and in the field Additional Include Directories
add the path to your .h file.
You can, also, as suggested by Chris Olen, add the path to VC++ Directories field.
You can use
hdfs fsck /
to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with
hdfs fsck / | egrep -v '^\.+$' | grep -v eplica
which ignores lines with nothing but dots and lines talking about replication.
Once you find a file that is corrupt
hdfs fsck /path/to/corrupt/file -locations -blocks -files
Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.
You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.
Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.
Once you determine what happened and you cannot recover any more blocks, just use the
hdfs fs -rm /path/to/file/with/permanently/missing/blocks
command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.
add this to you CSS:
html, body
{
height: 100%;
}
when you say to wrap
to be 100%
, 100% of what? of its parent (body), so his parent has to have some height.
and the same goes for body
, his parent his html
. html
parent his the viewport..
so, by setting them both to 100%, wrap
can also have a percentage height.
also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use
*
{
padding: 0;
margin: 0;
}
to disable that.
Look at That Fiddle
I use @senornestor 's solution, but to be entirely correct you have to remove the event listener as well:
componentDidMount() {
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount(){
window.removeEventListener('resize', this.handleResize);
}
handleResize = () => {
this.forceUpdate();
};
Otherwise you 'll get the warning:
Warning: forceUpdate(...): Can only update a mounted or mounting component. This usually means you called forceUpdate() on an unmounted component. This is a no-op. Please check the code for the XXX component.
I guess all other options would be more cryptic. For those who like readable and non-cryptic code:
IF "%ID%"=="0" (
REM do something
) ELSE IF "%ID%"=="1" (
REM do something else
) ELSE IF "%ID%"=="2" (
REM do another thing
) ELSE (
REM default case...
)
It's like an anecdote:
Magician: Put the egg under the hat, do the magic passes ... Remove the hat and ... get the same egg but in the side view ...
The IF
ELSE
solution isn't that bad. It's almost as good as python's if
elif
else
. More cryptic 'eggs' can be found here.
Try the Terminal Services PowerShell Module:
Get-TSSession -ComputerName comp1 -UserName user1 | Stop-TSSession -Force
A simple way is to write:
-std=c++11
in the Other Options section of the compiler flags. You could do this on a per-project basis (Project -> Build Options), and/or set it as a default option in the Settings -> Compilers part.
Some projects may require -std=gnu++11
which is like C++11 but has some GNU extensions enabled.
If using g++ 4.9, you can use -std=c++14
or -std=gnu++14
.
My site configuration file is example.conf in sites-available folder So you can create a symbolic link as
ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/
If the answers mentioned above are not working, you can try deleting all the files in data, except for the folder
Goto: C:\xampp\mysql\data
After that: Goto: C:\xampp\mysql\bin
then open with notepad my.ini , Its look like this.
Then delete or put into comment the port 3306 and change it to 8111 then run xamp with administrator and its work well.
The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.
Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).
The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.
In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.
If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.
Add white-space: nowrap;
:
.garage-title {
clear: both;
display: inline-block;
overflow: hidden;
white-space: nowrap;
}
It happened to me simply because of broken permissions. My user did not have read nor write access to that file. Fixing permissions fixed the problem
in a single try catch block you can do all the thing the best practice is to catch the error in different catch block if you want them to show with their own message for particular errors.
If you target android 5.0 and above. You could use:
Activity.startLockTask()
When creating a project from a sample,while not importing the existing project is good (prevents clashes with gradle, .idea, .iml, build, jars and apks, i.e. all unnecessary build-generated files), after creating a new project, copying and pasting all relevant resources, I'd recommend :
checking packages and imports from packages within the project {AndroidManifest declaration and all imports in java classes}, all resources (drawable, mip-map, layouts and menus & your build.gradle (a sample of build.gradle to use with the latest sdk can be provided on request)) to see if they are there & if declared strings and ids actually exist and have been used, after which your only error should be the question asked:
Bulid->Clean Project
Tools->Android->Sync Project with Gradle Files
File->Invalidate Caches and Restart
In worst cases restarting your machine helps.
The above should work. Feel free to ask questions if necessary, i.e. post comments.
It is because you are in a try
statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally
block, that way it will for sure be returned.
Make sure that you initialize sum outside the try/catch/finally
so that it is in scope.
Had the same problem and none of the CSS solutions presented here worked.
What worked for me was setting up a height="360" without setting any width. My photos aren't the same size and like this they have room to adjust their with but keep the height fixed.
Well that is Because of
you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception. and the one way is to encrypt that data Directly into the String.
look this. Try and u will be able to resolve this
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
String decordedValue = new BASE64Decoder().decodeBuffer(encryptedData).toString().trim();
System.out.println("This is Data to be Decrypted" + decordedValue);
return decordedValue;
}
hope that will help.
Differently from Dan, I consider his answer quite elegant... but unfortunately it is also very very inefficient. So, since the question mentioned "a large csv file", let me suggest to try in a shell Dan's solution:
time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print df['col'].apply(lambda x : pd.Series(x.split(' '))).head()"
... compared to this alternative:
time python -c "import pandas as pd;
from scipy import array, concatenate;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(concatenate(df['col'].apply( lambda x : [x.split(' ')]))).head()"
... and this:
time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(dict(zip(range(3), [df['col'].apply(lambda x : x.split(' ')[i]) for i in range(3)]))).head()"
The second simply refrains from allocating 100 000 Series, and this is enough to make it around 10 times faster. But the third solution, which somewhat ironically wastes a lot of calls to str.split() (it is called once per column per row, so three times more than for the others two solutions), is around 40 times faster than the first, because it even avoids to instance the 100 000 lists. And yes, it is certainly a little ugly...
EDIT: this answer suggests how to use "to_list()" and to avoid the need for a lambda. The result is something like
time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(df.col.str.split().tolist()).head()"
which is even more efficient than the third solution, and certainly much more elegant.
EDIT: the even simpler
time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print pd.DataFrame(list(df.col.str.split())).head()"
works too, and is almost as efficient.
EDIT: even simpler! And handles NaNs (but less efficient):
time python -c "import pandas as pd;
df = pd.DataFrame(['a b c']*100000, columns=['col']);
print df.col.str.split(expand=True).head()"
try
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
[CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [smalldatetime] NOT NULL
)
PS I think a smalldatetime is good enough. You may decide differently.
Can you not do this at the "moment of impact" ?
In Sql Server, this is common:
Update dbo.MyTable
Set
ColA = @SomeValue ,
UpdateDS = CURRENT_TIMESTAMP
Where...........
Sql Server has a "timestamp" datatype.
But it may not be what you think.
Here is a reference:
http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx
Here is a little RowVersion (synonym for timestamp) example:
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Maybe a complete working example:
DROP TABLE [dbo].[Names]
GO
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
GO
CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS
BEGIN
Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where
triggerInsertedTable.Name = myAlias.Name
END
GO
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Matching on the "Name" value is probably not wise.
Try this more mainstream example with a SurrogateKey
DROP TABLE [dbo].[Names]
GO
CREATE TABLE [dbo].[Names]
(
SurrogateKey int not null Primary Key Identity (1001,1),
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
GO
CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS
BEGIN
UPDATE dbo.Names
SET UpdateTS = CURRENT_TIMESTAMP
From dbo.Names myAlias
WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)
END
GO
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
I don't think it's a matter of being Pythonic or elegant. It's a matter of preventing exceptions as much as you can. Exceptions are meant to handle errors that might occur in code or events you have no control over.
In this case, you have full control when checking if an item is an attribute or in a dictionary, so avoid nested exceptions and stick with your second attempt.
If your Job is failing because of OutOfMemmory on nodes you can tweek your number of max maps and reducers and the JVM opts for each. mapred.child.java.opts (the default is 200Xmx) usually has to be increased based on your data nodes specific hardware.
This link might be helpful... pls check
According to Google documentation they said that this is the best way to do it. First create this function to find out how many markers there are/
function setMapOnAll(map1) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map1);
}
}
Next create another function to take away all these markers
function clearMarker(){
setMapOnAll(null);
}
Then create this final function to erase all the markers when ever this function is called upon.
function delateMarkers(){
clearMarker()
markers = []
//console.log(markers) This is just if you want to
}
Hope that helped good luck
Just using the command list did not work for me.
if you have a tuple just iterate until you have the elements there are necessary and after that append to a list. And if you go to the element level you can change it easily.
input:
level1 = (
(1,1,1,1,1,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,1,1,1,1,1))
level1_as_list=[]
for i in level1:
inside_list=[]
for j in i:
inside_list.append(j)
level1_as_list.append(inside_list)
print(level1_as_list)enter code here
output:
[[1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1]]
try setting both html
and body
to height 100%;
html, body {background: blue; height:100%;}
As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.
CUBRID (open source RDBMS) explains the idea of this two algorithms:
- Two-phase locking (2PL)
The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).
- Multi-version concurrency control (MVCC)
The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.
When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).
The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).
In 2PL Transaction isolation levels control the following:
Whether locks are taken when data is read, and what type of locks are requested.
How long the read locks are held.
Whether a read operation referencing rows modified by another transaction:
Block until the exclusive lock on the row is freed.
Retrieve the committed version of the row that existed at the time the statement or transaction started.
Read the uncommitted data modification.
Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.
A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.
Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)
READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]
READ_COMMITED:
REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.
SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.
I just ran this in terminal: sudo killall -9 mysqld
and then I force quit MAMP.
Reopen Mamp and everything works perfectly.
Sometimes, just turning off and restarting your computer does the trick.
Unfortunately, this is something you will have to ask you provider to do.
If your the owner of the server and can login to WHM it's under:
Tweak Settings => PHP Settings => Maximum Upload Size
Newer version have it listed under:
Home => Service Configuration => PHP Configuration Editor => Tweak Settings => PHP
I appreciate this wasn't the OP's issue, but I ran into this issue recently with a different cause. For reference, I was using the Liquibase Maven plugin (liquibase-maven-plugin:3.1.1) with SQL Server.
Anyway, I'd erroneously copied and pasted a SQL Server "use" statement into one of my scripts that switches databases, so liquibase was running and updating the DATABASECHANGELOGLOCK
, acquiring the lock in the correct database, but then switching databases to apply the changes. Not only could I NOT see my changes or liquibase audit in the correct database, but of course, when I ran liquibase again, it couldn't acquire the lock, as the lock had been released in the "wrong" database, and so was still locked in the "correct" database. I'd have expected liquibase to check the lock was still applied before releasing it, and maybe that is a bug in liquibase (I haven't checked yet), but it may well be addressed in later versions! That said, I suppose it could be considered a feature!
Quite a bit of a schoolboy error, I know, but I raise it here in case anyone runs into the same problem!
This is many years late but since I found the solution I'll post it here. By using maps it is possible to do what was asked:
map $http_host $variable_name {
hostnames;
default /ap/;
example.com /api/;
*.example.org /whatever/;
}
server {
location $variable_name/test {
proxy_pass $auth_proxy;
}
}
If you need to share the same endpoint across multiple servers, you can also reduce the cost by simply defaulting the value:
map "" $variable_name {
default /test/;
}
Map can be used to initialise a variable based on the content of a string and can be used inside http
scope allowing variables to be global and sharable across servers.
ListenForClients
is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main
. When two instances of the TcpListener
try to listen on the same port, you get that error.
"Error LNK1158 cannot run 'rc.exe" could be resulted from your project was opened by newer MS VS version. For instance, your project was created in VS 2015, then later was opened by 2017. Then later your project is opened in 2015.
To resolve this issue, open yourProjectName.vcxproj, look for WindowsTargetPlatformVersion, and change to the correct VS version
For VS 2015, it should be 8.1 for VS 2017, it should be 10.0.17763.0
Edit:
As some folks needs help in Unlocking device after locking programmatically, I came through post Android screen lock/ unlock programatically, please have look, may help you.
Original Answer was:
You need to get Admin permission and you can lock phone screen
please check below simple tutorial to achive this one
Lock Phone Screen Programmtically
also here is the code example..
LockScreenActivity.java
public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
MyAdmin.java
public class MyAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
@Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
@Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
@Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
@Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
@Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
Collapse to definitions
CTRL + M, O
Expand all outlining
CTRL + M, X
Expand or collapse everything
CTRL + M, L
This also works with other languages like TypeScript and JavaScript
Add include_directories("/your/path/here")
.
This will be similar to calling gcc
with -I/your/path/here/
option.
Make sure you put double quotes around the path. Other people didn't mention that and it made me stuck for 2 days. So this answer is for people who are very new to CMake and very confused.
It's a linker problem. Include the static library path into your project.
For Qt Creator open the project file .pro
and add the following line:
LIBS += -L<path for boost libraries in the system> -lboost_system
In my case Ubuntu x86_64:
LIBS += -L/usr/lib/x86_64-linux-gnu -lboost_system
For Codeblocks, open up Settings->Compiler...->Linker
settings tab and add:
boost_system
to the Link libraries text widget and press OK button.
Setting the underlying socket ReceiveTimeout
property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout
. You can read the docs for more information.
Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.
I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
var bytes = 0;
client.Client.ReceiveTimeout = 20;
do
{
try
{
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
catch (IOException ex)
{
// if the ReceiveTimeout is reached an IOException will be raised...
// with an InnerException of type SocketException and ErrorCode 10060
var socketExept = ex.InnerException as SocketException;
if (socketExept == null || socketExept.ErrorCode != 10060)
// if it's not the "expected" exception, let's not hide the error
throw ex;
// if it is the receive timeout, then reading ended
bytes = 0;
}
} while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)
#include <iostream>
int main()
{
std::cout<<"Hello World!\n";
return 0;
}
After adding the icon to the toolbar and when modifying the selected icon, the ampersand in the name input is specifying that the next character is the character used along with Alt for the shortcut. Since you must select a display option from the Modify Selection drop down menu that includes displaying the text, you could also write &C in the name field and get the same result as &Comment Block (without the lengthy text).
You can use a defaultdict for this.
from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')
This is slightly more efficient than setdefault
since you don't end up creating new lists that you don't end up using. Every call to setdefault
is going to create a new list, even if the item already exists in the dictionary.
I got this error generating a data frame consisting of timestamps and data:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))
Adding the suggested solution works for me:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))
Thanks Chang She!
Example:
data
2005-01-01 00:10:00 7.53
2005-01-01 00:20:00 7.54
2005-01-01 00:30:00 7.62
2005-01-01 00:40:00 7.68
2005-01-01 00:50:00 7.81
2005-01-01 01:00:00 7.95
2005-01-01 01:10:00 7.96
2005-01-01 01:20:00 7.95
2005-01-01 01:30:00 7.98
2005-01-01 01:40:00 8.06
2005-01-01 01:50:00 8.04
2005-01-01 02:00:00 8.06
2005-01-01 02:10:00 8.12
2005-01-01 02:20:00 8.12
2005-01-01 02:30:00 8.25
2005-01-01 02:40:00 8.27
2005-01-01 02:50:00 8.17
2005-01-01 03:00:00 8.21
2005-01-01 03:10:00 8.29
2005-01-01 03:20:00 8.31
2005-01-01 03:30:00 8.25
2005-01-01 03:40:00 8.19
2005-01-01 03:50:00 8.17
2005-01-01 04:00:00 8.18
data
2005-01-01 00:00:00 7.636000
2005-01-01 01:00:00 7.990000
2005-01-01 02:00:00 8.165000
2005-01-01 03:00:00 8.236667
2005-01-01 04:00:00 8.180000
You need to link with the math library:
gcc -o sphere sphere.c -lm
The error you are seeing: error: ld returned 1 exit status
is from the linker ld
(part of gcc that combines the object files) because it is unable to find where the function pow
is defined.
Including math.h
brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a
. You need to link your program with this library so that the calls to functions like pow() are resolved.
You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:
ManualResetEvent oSignalEvent = new ManualResetEvent(false);
void SecondThread(){
//DoStuff
oSignalEvent.Set();
}
void Main(){
//DoStuff
//Call second thread
System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
oSecondThread.Start();
oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
oSignalEvent.Reset();
//Do more stuff
}
An alternative solution is just to remove the 'dropdown-toggle' class from the anchor. After this clicking will no longer trigger the dropwon.js, so you may want to have the submenu to show on hover.
The SELECT WITH (NOLOCK)
allows reads of uncommitted data, which is equivalent to having the READ UNCOMMITTED
isolation level set on your database. The NOLOCK
keyword allows finer grained control than setting the isolation level on the entire database.
Wikipedia has a useful article: Wikipedia: Isolation (database systems)
It is also discussed at length in other stackoverflow articles.
You can also simply use this:
.bg_rgba {
background: linear-gradient(0deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.9)), url('https://picsum.photos/200');
width: 200px;
height: 200px;
border: 1px solid black;
}
_x000D_
<div class='bg_rgba'></div>
_x000D_
You can change the opacity of the color to your preference.
its very simple
just write:
//first create table named test....
create table test (name varchar2(10),age number(5));
//when you run the above code a table will be created....
//now we have to insert a name & an age..
Make sure age will be inserted via opening a form that seeks our help to enter the value in it
insert into test values('Deepak', :age);
//now run the above code and you'll get "1 row inserted" output...
/now run the select query to see the output
select * from test;
//that's all ..Now i think no one has any queries left over accepting a user data...
Exactly how to do this depends on the version of Jackson that you're using. This changed around version 1.9, before that, you could do this by adding @JsonIgnore
to the getter.
Which you've tried:
Add @JsonIgnore on the getter method only
Do this, and also add a specific @JsonProperty
annotation for your JSON "password" field name to the setter method for the password on your object.
More recent versions of Jackson have added READ_ONLY
and WRITE_ONLY
annotation arguments for JsonProperty
. So you could also do something like:
@JsonProperty(access = Access.WRITE_ONLY)
private String password;
Docs can be found here.
In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.
I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:
DBCC TRACEON(1222, -1);
A quick search yielded this tutorial:
http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/
Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.
Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:
Disclaimer: I work for SQL Sentry.
To answer this point:
I want Sleep to be an async method so it can await other methods
you can maybe rewrite the Sleep
function like this:
private static async Task<int> Sleep(int ms)
{
Console.WriteLine("Sleeping for " + ms);
var task = Task.Run(() => Thread.Sleep(ms));
await task;
Console.WriteLine("Sleeping for " + ms + "END");
return ms;
}
static void Main(string[] args)
{
Console.WriteLine("Starting");
var task1 = Sleep(2000);
var task2 = Sleep(1000);
int totalSlept = task1.Result +task2.Result;
Console.WriteLine("Slept for " + totalSlept + " ms");
Console.ReadKey();
}
running this code will output :
Starting
Sleeping for 2000
Sleeping for 1000
*(one second later)*
Sleeping for 1000END
*(one second later)*
Sleeping for 2000END
Slept for 3000 ms
Demo at http://jsfiddle.net/CRSVU/
html,
body {
height: 100%;
padding: 0;
margin: 0;
}
div {
width: 50%;
height: 50%;
float: left;
}
#div1 {
background: #DDD;
}
#div2 {
background: #AAA;
}
#div3 {
background: #777;
}
#div4 {
background: #444;
}
_x000D_
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
_x000D_
Do you want to keep your database on mobile? Use sqlite instead of mysql.
If the idea is to keep database on server and access from mobile. Use a webservice to fetch/ modify data.
I didn't check all the code but my guess is that the error is in the malloc call. You have to replace
double *ptr = malloc(sizeof(double*) * TIME);
for
double *ptr = malloc(sizeof(double) * TIME);
since you want to allocate size for a double (not the size of a pointer to a double).
I know you asked about GCD, but if you wanted, NSOperationQueue
also handles this sort of stuff really gracefully, e.g.:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Starting 3");
}];
NSOperation *operation;
operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Starting 1");
sleep(7);
NSLog(@"Finishing 1");
}];
[completionOperation addDependency:operation];
[queue addOperation:operation];
operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Starting 2");
sleep(5);
NSLog(@"Finishing 2");
}];
[completionOperation addDependency:operation];
[queue addOperation:operation];
[queue addOperation:completionOperation];
Put very simple ::
is the scoping operator, .
is the access operator (I forget what the actual name is?), and ->
is the dereference arrow.
::
- Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it. If you are using this operator to call a function, the function is a static
function.
.
- This allows access to a member function on an already created object. For instance, Foo x; x.bar()
calls the method bar()
on instantiated object x
which has type Foo
. You can also use this to access public class variables.
->
- Essentially the same thing as .
except this works on pointer types. In essence it dereferences the pointer, than calls .
. Using this is equivalent to (*ptr).method()
I'd wonder why someone would try to "override" the container width, since its purpose is to keep its content with some padding, but I had a similar situation (that's why I wanted to share my solution, even though there're answers).
In my situation, I wanted to have all content (of all pages) rendered inside a container, so this was the piece of code from my _Layout.cshtml:
<div id="body">
@RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
<div class="container">
@RenderBody()
</div>
</section>
</div>
In my Home Index page, I had a background header image I'd like to fill the whole screen width, so the solution was to make the Index.cshtml like this:
@section featured {
<!-- This content will be rendered outside the "container div" -->
<div class="intro-header">
<div class="container">SOME CONTENT WITH A NICE BACKGROUND</div>
</div>
}
<!-- The content below will be rendered INSIDE the "container div" -->
<div class="content-section-b">
<div class="container">
<div class="row">
MORE CONTENT
</div>
</div>
</div>
I think this is better than trying to make workarounds, since sections are made with the purpose of allowing (or forcing) views to dynamically replace some content in the layout.
Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.
They should be
server {
listen 80;
server_name www.domain1.com;
root /var/www/domain1;
}
server {
listen 80;
server_name www.domain2.com;
root /var/www/domain2;
}
Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.
create table abc(emp_ID int, manager varchar(20) , manager_id int)
emp_ID manager manager_id
1 abc NULL
2 def 1
3 ghi 2
4 klm 3
5 def1 1
6 ghi1 2
7 klm1 3
select a.emp_ID , a.manager emp_name,b.manager manager_name
from abc a
left join abc b
on a.manager_id = b.emp_ID
Result:
emp_ID emp_name manager_name
1 abc NULL
2 def abc
3 ghi def
4 klm ghi
5 def1 abc
6 ghi1 def
7 klm1 ghi
Branch-prediction gain!
It is important to understand that branch misprediction doesn't slow down programs. The cost of a missed prediction is just as if branch prediction didn't exist and you waited for the evaluation of the expression to decide what code to run (further explanation in the next paragraph).
if (expression)
{
// Run 1
} else {
// Run 2
}
Whenever there's an if-else
\ switch
statement, the expression has to be evaluated to determine which block should be executed. In the assembly code generated by the compiler, conditional branch instructions are inserted.
A branch instruction can cause a computer to begin executing a different instruction sequence and thus deviate from its default behavior of executing instructions in order (i.e. if the expression is false, the program skips the code of the if
block) depending on some condition, which is the expression evaluation in our case.
That being said, the compiler tries to predict the outcome prior to it being actually evaluated. It will fetch instructions from the if
block, and if the expression turns out to be true, then wonderful! We gained the time it took to evaluate it and made progress in the code; if not then we are running the wrong code, the pipeline is flushed, and the correct block is run.
Let's say you need to pick route 1 or route 2. Waiting for your partner to check the map, you have stopped at ## and waited, or you could just pick route1 and if you were lucky (route 1 is the correct route), then great you didn't have to wait for your partner to check the map (you saved the time it would have taken him to check the map), otherwise you will just turn back.
While flushing pipelines is super fast, nowadays taking this gamble is worth it. Predicting sorted data or a data that changes slowly is always easier and better than predicting fast changes.
O Route 1 /-------------------------------
/|\ /
| ---------##/
/ \ \
\
Route 2 \--------------------------------
The list from 2020-05-23 is:
31.13.24.0/21
31.13.64.0/18
45.64.40.0/22
66.220.144.0/20
69.63.176.0/20
69.171.224.0/19
74.119.76.0/22
102.132.96.0/20
103.4.96.0/22
129.134.0.0/16
147.75.208.0/20
157.240.0.0/16
173.252.64.0/18
179.60.192.0/22
185.60.216.0/22
185.89.216.0/22
199.201.64.0/22
204.15.20.0/22
The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:
whois -h whois.radb.net -- '-i origin AS32934' | grep ^route
Here's my code Example for if..else..if
which do the following
Prompt user for Process Name
If the process name is invalid
Then it's write to user
Error : The Processor above doesn't seem to be exist
if the process name is services
Then it's write to user
Error : You can't kill the Processor above
if the process name is valid and not services
Then it's write to user
the process has been killed via taskill
so i called it Process killer.bat
Here's my Code:
@echo off
:Start
Rem preparing the batch
cls
Title Processor Killer
Color 0B
Echo Type Processor name to kill It (Without ".exe")
set /p ProcessorTokill=%=%
:tasklist
tasklist|find /i "%ProcessorTokill%.exe">nul & if errorlevel 1 (
REM check if the process name is invalid
Cls
Title %ProcessorTokill% Not Found
Color 0A
echo %ProcessorTokill%
echo Error : The Processor above doesn't seem to be exist
) else if %ProcessorTokill%==services (
REM check if the process name is services and doesn't kill it
Cls
Color 0c
Title Permission denied
echo "%ProcessorTokill%.exe"
echo Error : You can't kill the Processor above
) else (
REM if the process name is valid and not services
Cls
Title %ProcessorTokill% Found
Color 0e
echo %ProcessorTokill% Found
ping localhost -n 2 -w 1000>nul
echo Killing %ProcessorTokill% ...
taskkill /f /im %ProcessorTokill%.exe /t>nul
echo %ProcessorTokill% Killed...
)
pause>nul
REM If else if Template
REM if thing1 (
REM Command here 2 !
REM ) else if thing2 (
REM command here 2 !
REM ) else (
REM command here 3 !
REM )
Starting with MySQL 5.7, the performance schema exposes all metadata locks, including locks related to the GET_LOCK()
function.
See http://dev.mysql.com/doc/refman/5.7/en/metadata-locks-table.html
Trie Data Structure can be used to store data in O(L)
where L is the length of the string so for inserting N strings time complexity would be O(NL)
the string can be searched in O(L)
only same goes for deletion.
Can be clone from https://github.com/Parikshit22/pytrie.git
class Node:
def __init__(self):
self.children = [None]*26
self.isend = False
class trie:
def __init__(self,):
self.__root = Node()
def __len__(self,):
return len(self.search_byprefix(''))
def __str__(self):
ll = self.search_byprefix('')
string = ''
for i in ll:
string+=i
string+='\n'
return string
def chartoint(self,character):
return ord(character)-ord('a')
def remove(self,string):
ptr = self.__root
length = len(string)
for idx in range(length):
i = self.chartoint(string[idx])
if ptr.children[i] is not None:
ptr = ptr.children[i]
else:
raise ValueError("Keyword doesn't exist in trie")
if ptr.isend is not True:
raise ValueError("Keyword doesn't exist in trie")
ptr.isend = False
return
def insert(self,string):
ptr = self.__root
length = len(string)
for idx in range(length):
i = self.chartoint(string[idx])
if ptr.children[i] is not None:
ptr = ptr.children[i]
else:
ptr.children[i] = Node()
ptr = ptr.children[i]
ptr.isend = True
def search(self,string):
ptr = self.__root
length = len(string)
for idx in range(length):
i = self.chartoint(string[idx])
if ptr.children[i] is not None:
ptr = ptr.children[i]
else:
return False
if ptr.isend is not True:
return False
return True
def __getall(self,ptr,key,key_list):
if ptr is None:
key_list.append(key)
return
if ptr.isend==True:
key_list.append(key)
for i in range(26):
if ptr.children[i] is not None:
self.__getall(ptr.children[i],key+chr(ord('a')+i),key_list)
def search_byprefix(self,key):
ptr = self.__root
key_list = []
length = len(key)
for idx in range(length):
i = self.chartoint(key[idx])
if ptr.children[i] is not None:
ptr = ptr.children[i]
else:
return None
self.__getall(ptr,key,key_list)
return key_list
t = trie()
t.insert("shubham")
t.insert("shubhi")
t.insert("minhaj")
t.insert("parikshit")
t.insert("pari")
t.insert("shubh")
t.insert("minakshi")
print(t.search("minhaj"))
print(t.search("shubhk"))
print(t.search_byprefix('m'))
print(len(t))
print(t.remove("minhaj"))
print(t)
True
False
['minakshi', 'minhaj']
7
minakshi
minhajsir
pari
parikshit
shubh
shubham
shubhi
This is a FAQ. You can put //NOSONAR
on the line triggering the warning. I prefer using the FindBugs mechanism though, which consists in adding the @SuppressFBWarnings annotation:
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
value = "NAME_OF_THE_FINDBUGS_RULE_TO_IGNORE",
justification = "Why you choose to ignore it")
Add 'center-block' to image as class - no additional css needed
<img src="images/default.jpg" class="center-block img-responsive"/>
If for a block cipher you're not going to use a Cipher
transformation that includes a padding scheme, you need to have the number of bytes in the plaintext be an integral multiple of the block size of the cipher.
So either pad out your plaintext to a multiple of 16 bytes (which is the AES block size), or specify a padding scheme when you create your Cipher
objects. For example, you could use:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Unless you have a good reason not to, use a padding scheme that's already part of the JCE implementation. They've thought out a number of subtleties and corner cases you'll have to realize and deal with on your own otherwise.
Ok, your second problem is that you are using String
to hold the ciphertext.
In general,
String s = new String(someBytes);
byte[] retrievedBytes = s.getBytes();
will not have someBytes
and retrievedBytes
being identical.
If you want/have to hold the ciphertext in a String
, base64-encode the ciphertext bytes first and construct the String
from the base64-encoded bytes. Then when you decrypt you'll getBytes()
to get the base64-encoded bytes out of the String
, then base64-decode them to get the real ciphertext, then decrypt that.
The reason for this problem is that most (all?) character encodings are not capable of mapping arbitrary bytes to valid characters. So when you create your String
from the ciphertext, the String
constructor (which applies a character encoding to turn the bytes into characters) essentially has to throw away some of the bytes because it can make no sense of them. Thus, when you get bytes out of the string, they are not the same bytes you put into the string.
In Java (and in modern programming in general), you cannot assume that one character = one byte, unless you know absolutely you're dealing with ASCII. This is why you need to use base64 (or something like it) if you want to build strings from arbitrary bytes.
Unique key allows max 2 NULL values. Explaination:
create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)
insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')
select * from teppp
null string , address1
NULL,address2
NULL,address3
If you try inserting same values as below:
insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')
Every time you will get error like:
Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.
In Windows 10, similar steps can be followed in other versions of windows.
Right Click on "My Computer" select Properties, Goto Advanced System Settings -> Advanced -> Select "Environment Variables.." .
Find "Path" select it and choose edit option -> Click on New and add "C:\MinGW\bin" (or the location of gcc.exe, if you have installed at some other location) -> Save and restart command prompt. Gcc should work.
This can be done with setjmp/longjmp
in C. P99 has a quite comfortable toolset for this that also is consistent with the new thread model of C11.
You've pretty much nailed it, however Mustache templates can also be compiled.
Mustache is missing helpers and the more advanced blocks because it strives to be logicless. Handlebars' custom helpers can be very useful, but often end up introducing logic into your templates.
Mustache has many different compilers (JavaScript, Ruby, Python, C, etc.). Handlebars began in JavaScript, now there are projects like django-handlebars, handlebars.java, handlebars-ruby, lightncandy (PHP), and handlebars-objc.
import threading
# global variable x
x = 0
def increment():
"""
function to increment global variable x
"""
global x
x += 1
def thread_task():
"""
task for thread
calls increment function 100000 times.
"""
for _ in range(100000):
increment()
def main_task():
global x
# setting global variable x as 0
x = 0
# creating threads
t1 = threading.Thread(target=thread_task)
t2 = threading.Thread(target=thread_task)
# start threads
t1.start()
t2.start()
# wait until threads finish their job
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(10):
main_task()
print("Iteration {0}: x = {1}".format(i,x))
This is a very old question, but my answer may help someone.
Below is the working code
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionDecryptionUtil {
public static String encrypt(final String secret, final String data) {
byte[] decodedKey = Base64.getDecoder().decode(secret);
try {
Cipher cipher = Cipher.getInstance("AES");
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
cipher.init(Cipher.ENCRYPT_MODE, originalKey);
byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(cipherText);
} catch (Exception e) {
throw new RuntimeException(
"Error occured while encrypting data", e);
}
}
public static String decrypt(final String secret,
final String encryptedString) {
byte[] decodedKey = Base64.getDecoder().decode(secret);
try {
Cipher cipher = Cipher.getInstance("AES");
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
cipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
return new String(cipherText);
} catch (Exception e) {
throw new RuntimeException(
"Error occured while decrypting data", e);
}
}
public static void main(String[] args) {
String data = "This is not easy as you think";
String key = "---------------------------------";
String encrypted = encrypt(key, data);
System.out.println(encrypted);
System.out.println(decrypt(key, encrypted));
}
}
For Generating Key you can use below class
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class SecretKeyGenerator {
public static void main(String[] args) throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
int keyBitSize = 256;
keyGenerator.init(keyBitSize, secureRandom);
SecretKey secretKey = keyGenerator.generateKey();
System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
}
}
diplay:flex;
is another alternative answer that you can add to all above answers which is supported in all modern browsers.
#block_container {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div id="block_container">_x000D_
<div id="bloc1">Copyright © All Rights Reserved.</div>_x000D_
<div id="bloc2"><img src="..."></div>_x000D_
</div>
_x000D_
This answer is outdated. You can do this a lot more simply, as pointed out in another answer below:
ul {
list-style-position: outside;
}
See https://www.w3schools.com/cssref/pr_list-style-position.asp
I'm surprised to see this hasn't been solved yet. You can make use of the browser's table layout algorithm (without using tables) like this:
ol {
counter-reset: foo;
display: table;
}
ol > li {
counter-increment: foo;
display: table-row;
}
ol > li::before {
content: counter(foo) ".";
display: table-cell; /* aha! */
text-align: right;
}
Demo: http://jsfiddle.net/4rnNK/1/
To make it work in IE8, use the legacy :before
notation with one colon.
Taking advantage of @skip405's answer, I've made a Sass mixin for it:
@mixin inline-block-lr($container,$left,$right){
#{$container}{
text-align: justify;
&:after{
content: '';
display: inline-block;
width: 100%;
height: 0;
font-size:0;
line-height:0;
}
}
#{$left} {
display: inline-block;
vertical-align: middle;
}
#{$right} {
display: inline-block;
vertical-align: middle;
}
}
It accepts 3 parameters. The container, the left and the right element. For example, to fit the question, you could use it like this:
@include inline-block-lr('header', 'h1', 'nav');
There are a number of people with this difficulty. The prevailing answer is that you can't protect content from editing while allowing unhindered sorting. Your options are:
1) Allow editing and sorting :(
2) Apply protection and create buttons with code to sort using VBA. There are other posts explaining how to do this. I think there are two methods, either (1) get the code to unprotect the sheet, apply the sort, then re-protect the sheet, or (2) have the sheet protected using UserInterfaceOnly:=True
.
3) Lorie's answer which does not allow users to select cells (https://stackoverflow.com/a/15390698/269953)
4) One solution that I haven't seen discussed is using VBA to provide some basic protection. For example, detect and revert changes using Worksheet_Change
. It's far from an ideal solution however.
5) You could keep the sheet protected when the user is selecting the data and unprotected when the user has the header is selected. This leaves countless ways the users could mess up the data while also causing some usability issues, but at least reduces the odds of pesky co-workers thoughtlessly making unwanted changes.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If (Target.row = HEADER_ROW) Then
wsMainTable.Unprotect Password:=PROTECTION_PASSWORD
Else
wsMainTable.Protect Password:=PROTECTION_PASSWORD, UserInterfaceOnly:=True
End If
End Sub
In a case
statement, a ,
is the equivalent of ||
in an if
statement.
case car
when 'toyota', 'lexus'
# code
end
Too many!
The "ANSI C" way buffer is redundant, since a FILE
is already buffered. (The size of this internal buffer is what BUFSIZ
actually defines.)
The "OWN-BUFFER-C++-WAY" will be slow as it goes through fstream
, which does a lot of virtual dispatching, and again maintains internal buffers or each stream object. (The "COPY-ALGORITHM-C++-WAY" does not suffer this, as the streambuf_iterator
class bypasses the stream layer.)
I prefer the "COPY-ALGORITHM-C++-WAY", but without constructing an fstream
, just create bare std::filebuf
instances when no actual formatting is needed.
For raw performance, you can't beat POSIX file descriptors. It's ugly but portable and fast on any platform.
The Linux way appears to be incredibly fast — perhaps the OS let the function return before I/O was finished? In any case, that's not portable enough for many applications.
EDIT: Ah, "native Linux" may be improving performance by interleaving reads and writes with asynchronous I/O. Letting commands pile up can help the disk driver decide when is best to seek. You might try Boost Asio or pthreads for comparison. As for "can't beat POSIX file descriptors"… well that's true if you're doing anything with the data, not just blindly copying.
Modern processors are too fast to register the running time. Hence it may return zero. In this case, the time you started and ended is too small and therefore both the times are the same after round of.
The easiest solution working fine for me is this:
export CFLAGS=-ggdb
export CXXFLAGS=-ggdb
CMake will append them to all configurations' flags. Just make sure to clear CMake cache.
The question specifically states the performance needs to be improved for ad-hoc queries, and that indexes can't be added. So taking that at face value, what can be done to improve performance on any table?
Since we're considering ad-hoc queries, the WHERE clause and the ORDER BY clause can contain any combination of columns. This means that almost regardless of what indexes are placed on the table there will be some queries that require a table scan, as seen above in query plan of a poorly performing query.
Taking this into account, let's assume there are no indexes at all on the table apart from a clustered index on the primary key. Now let's consider what options we have to maximize performance.
Defragment the table
As long as we have a clustered index then we can defragment the table using DBCC INDEXDEFRAG (deprecated) or preferably ALTER INDEX. This will minimize the number of disk reads required to scan the table and will improve speed.
Use the fastest disks possible. You don't say what disks you're using but if you can use SSDs.
Optimize tempdb. Put tempdb on the fastest disks possible, again SSDs. See this SO Article and this RedGate article.
As stated in other answers, using a more selective query will return less data, and should be therefore be faster.
Now let's consider what we can do if we are allowed to add indexes.
If we weren't talking about ad-hoc queries, then we would add indexes specifically for the limited set of queries being run against the table. Since we are discussing ad-hoc queries, what can be done to improve speed most of the time?
Edit
I've run some tests on a 'large' table of 22 million rows. My table only has six columns but does contain 4GB of data. My machine is a respectable desktop with 8Gb RAM and a quad core CPU and has a single Agility 3 SSD.
I removed all indexes apart from the primary key on the Id column.
A similar query to the problem one given in the question takes 5 seconds if SQL server is restarted first and 3 seconds subsequently. The database tuning advisor obviously recommends adding an index to improve this query, with an estimated improvement of > 99%. Adding an index results in a query time of effectively zero.
What's also interesting is that my query plan is identical to yours (with the clustered index scan), but the index scan accounts for 9% of the query cost and the sort the remaining 91%. I can only assume your table contains an enormous amount of data and/or your disks are very slow or located over a very slow network connection.
There are two parts to that answer (I wrote it). One part is easy to quantify, the other is more empirical.
This is the easy to quantify part. Appendix F of the current CUDA programming guide lists a number of hard limits which limit how many threads per block a kernel launch can have. If you exceed any of these, your kernel will never run. They can be roughly summarized as:
If you stay within those limits, any kernel you can successfully compile will launch without error.
This is the empirical part. The number of threads per block you choose within the hardware constraints outlined above can and does effect the performance of code running on the hardware. How each code behaves will be different and the only real way to quantify it is by careful benchmarking and profiling. But again, very roughly summarized:
The second point is a huge topic which I doubt anyone is going to try and cover it in a single StackOverflow answer. There are people writing PhD theses around the quantitative analysis of aspects of the problem (see this presentation by Vasily Volkov from UC Berkley and this paper by Henry Wong from the University of Toronto for examples of how complex the question really is).
At the entry level, you should mostly be aware that the block size you choose (within the range of legal block sizes defined by the constraints above) can and does have a impact on how fast your code will run, but it depends on the hardware you have and the code you are running. By benchmarking, you will probably find that most non-trivial code has a "sweet spot" in the 128-512 threads per block range, but it will require some analysis on your part to find where that is. The good news is that because you are working in multiples of the warp size, the search space is very finite and the best configuration for a given piece of code relatively easy to find.
To make it simple, you can think of it like that;
break
command in the for
loop, the else
part will not be called.break
command in the for
loop, the else
part will be called.In other words, if for loop iteration is not "broken" with break
, the else
part will be called.
Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html
I had the same problem, It was solved when I checked the below checkbox
Include externals
A volatile + synchronization is a fool proof solution for an operation(statement) to be fully atomic which includes multiple instructions to the CPU.
Say for eg:volatile int i = 2; i++, which is nothing but i = i + 1; which makes i as the value 3 in the memory after the execution of this statement. This includes reading the existing value from memory for i(which is 2), load into the CPU accumulator register and do with the calculation by increment the existing value with one(2 + 1 = 3 in accumulator) and then write back that incremented value back to the memory. These operations are not atomic enough though the value is of i is volatile. i being volatile guarantees only that a SINGLE read/write from memory is atomic and not with MULTIPLE. Hence, we need to have synchronized also around i++ to keep it to be fool proof atomic statement. Remember the fact that a statement includes multiple statements.
Hope the explanation is clear enough.
This : /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i
is not working for below Gmail case
[email protected] [email protected]
Below Regex will cover all the E-mail Points: I have tried the all Possible Points and my Test case get also pass because of below regex
I found this Solution from this URL:
/(?:((?:[\w-]+(?:\.[\w-]+)*)@(?:(?:[\w-]+\.)*\w[\w-]{0,66})\.(?:[a-z]{2,6}(?:\.[a-z]{2})?));*)/g
Didnt work for me.
I created a new key and string value and managed to get it working
Key= HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\<Your app name>\
String EventMessageFile value=C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll
I am going to assume you only want this to be in effect while your application is in the foreground.
This code:
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
Does not turn the screen off in the traditional sense. It makes the screen as dim as possible. In the standard platform there is a limit to how dim it can be; if your device is actually allowing the screen to turn completely off, then it is some peculiarity of the implementation of that device and not a behavior you can count on across devices.
In fact using this in conjunction with FLAG_KEEP_SCREEN_ON means that you will never allow the screen to go off (and thus the device to go into low-power mode) even if the particular device is allowing you to set the screen brightness to full-off. Keep this very strongly in mind. You will be using much more power than you would if the screen was really off.
Now for turning the screen back to regular brightness, just setting the brightness value should do it:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = -1;
getWindow().setAttributes(params);
I can't explain why this wouldn't replace the 0 value you had previously set. As a test, you could try putting a forced full brightness in there to force to that specific brightness:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1;
getWindow().setAttributes(params);
This definitely works. For example, Google's Books apps uses this to allow you to set the screen brightness to dim while using a book and then return to regular brightness when turning that off.
To help debug, you can use "adb shell dumpsys window" to see the current state of your window. In the data for your window, it will tell you the current LayoutParams that have been set for it. Ensure the value you think is actually there.
And again, FLAG_KEEP_SCREEN_ON is a separate concept; it and the brightness have no direct impact on each other. (And there would be no reason to set the flag again when undoing the brightness, if you had already set it when putting the brightness to 0. The flag will stay set until you change it.)
I would use a macro to record my actions and would then repeat it.
You now have a nice macro.
Type 3@q to execute your macro three times to do the rest of the lines.
char a[2]
defines an array of char
's. a
is a pointer to the memory at the beginning of the array and using ==
won't actually compare the contents of a
with 'ab'
because they aren't actually the same types, 'ab'
is integer type. Also 'ab'
should be "ab"
otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.
Something that might be illustrative is looking at the typeid
of 'ab'
:
#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
int some_int =5;
std::cout << typeid('ab').name() << std::endl;
std::cout << typeid(some_int).name() << std::endl;
return 0;
}
on my system this returns:
i
i
showing that 'ab'
is actually evaluated as an int.
If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator ==
overloaded and will do a comparison check when called this way.
If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:
#include <iostream>
#include <string>
using namespace std;
int main(){
string a;
cout<<"enter ab ";
cin>>a;
if(a=="ab"){
cout<<"correct";
}
return 0;
}
This one is due to:
if(a=='ab')
, here, a
is const char*
type (ie : array of char)
'ab'
is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.
Since char
is a primitive type inherited from C, no operator ==
is defined.
the good code should be:
if(strcmp(a,"ab")==0)
, then you'll compare a const char*
to another const char*
using strcmp
.
In my case I was trying to create a table from one database to another on MS SQL Server 2012. Right-clicking on a table and selecting Script Table as > DROP And CREATE To > New Query Editor Window, following script was created:
USE [SAMPLECOMPANY]
GO
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [FK_Employees_Departments]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
DROP TABLE [dbo].[Employees]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[DepartmentId] [int] NOT NULL,
[FullName] [varchar](50) NOT NULL,
[HireDate] [datetime] NULL
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Employees] WITH CHECK ADD CONSTRAINT [FK_Employees_Departments] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Departments] ([DepartmentID])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO
However when executing above script it was returning the error:
SELECT failed because the following SET options have incorrect settings: 'ANSI_PADDING'. Verify that SET options are correct for use with indexed views and/or indexes on computed columns and/or filtered indexes and/or query notifications and/or XML data type methods and/or spatial index operations.
The Solution I've found: Enabling the settings on the Top of the script like this:
USE [SAMPLECOMPANY]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [FK_Employees_Departments]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
DROP TABLE [dbo].[Employees]
GO
CREATE TABLE [dbo].[Employees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[DepartmentId] [int] NOT NULL,
[FullName] [varchar](50) NOT NULL,
[HireDate] [datetime] NULL
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Employees] WITH CHECK ADD CONSTRAINT [FK_Employees_Departments] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Departments] ([DepartmentID])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO
SET ANSI_PADDING OFF
GO
Hope this help.
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
Just for others who may look at this answer in the hope of solving a similar problem, I got a similar message because my ip address changed.
java.net.BindException: Cannot assign requested address: bind
at sun.nio.ch.Net.bind(Native Method)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:126)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:59)
at org.eclipse.jetty.server.nio.SelectChannelConnector.open(SelectChannelConnector.java:182)
at org.eclipse.jetty.server.AbstractConnector.doStart(AbstractConnector.java:311)
at org.eclipse.jetty.server.nio.SelectChannelConnector.doStart(SelectChannelConnector.java:260)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at org.eclipse.jetty.server.Server.doStart(Server.java:273)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
With WinForms you can use the ErrorProvider in conjunction with the Validating
event to handle the validation of user input. The Validating
event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.
http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx
For some reason neither style="Widget.Holo.Button.Borderless"
nor android:background="?android:attr/selectableItemBackground"
worked for me. To be more precise Widget.Holo.Button.Borderless
did the job on Android 4.0 but didn't work on Android 2.3.3. What did the trick for me on both versions was android:background="@drawable/transparent"
and this XML in res/drawable/transparent.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
</shape>
Plain head through the wall approach.
As per the official docs the sp_lock is mark as deprecated:
This feature is in maintenance mode and may be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.
and it is recommended to use sys.dm_tran_locks instead. This dynamic management object returns information about currently active lock manager resources. Each row represents a currently active request to the lock manager for a lock that has been granted or is waiting to be granted.
It generally returns more details in more user friendly syntax then sp_lock
does.
The whoisactive routine written by Adam Machanic is very good to check the current activity in your environment and see what types of waits/locks are slowing your queries. You can very easily find what is blocking your queries and tons of other handy information.
For example, let's say we have the following queries running in the default SQL Server Isolation Level - Read Committed. Each query is executing in separate query window:
-- creating sample data
CREATE TABLE [dbo].[DataSource]
(
[RowID] INT PRIMARY KEY
,[RowValue] VARCHAR(12)
);
INSERT INTO [dbo].[DataSource]([RowID], [RowValue])
VALUES (1, 'samle data');
-- query window 1
BEGIN TRANSACTION;
UPDATE [dbo].[DataSource]
SET [RowValue] = 'new data'
WHERE [RowID] = 1;
--COMMIT TRANSACTION;
-- query window 2
SELECT *
FROM [dbo].[DataSource];
Then execute the sp_whoisactive
(only part of the columns are displayed):
You can easily seen the session which is blocking the SELECT
statement and even its T-SQL code. The routine has a lot of parameters, so you can check the docs for more details.
If we query the sys.dm_tran_locks
view we can see that one of the session is waiting for a share lock of a resource, that has exclusive lock by other session:
The problem seems to be that block
elements only scale up to 100% of their containing element, no matter how big their content is—it just overflows. However, making them inline-block
elements apparently resizes their width to their actual content.
HTML:
<div id="container">
<div class="wide">
foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
</div>
<div class="wide">
bar
</div>
</div>
CSS:
.wide { min-width: 100%; display: inline-block; background-color: yellow; }
#container { display: inline-block; }
(The container
element addresses your follow-up question to make the second div
as big as the previous one, and not just the screen width.)
I also set up a JS fiddle showing my demo code.
If you run into any troubles (esp. cross-browser issues) with inline-block
, looking at Block-level elements within display: inline-block might help.
I came across this error while attempting to pass an un-encrypted file path to the Decrypt method.The solution was to check if the passed file is encrypted first before attempting to decrypt
if (Sec.IsFileEncrypted(e.File.FullName))
{
var stream = Sec.Decrypt(e.File.FullName);
}
else
{
// non-encrypted scenario
}
It's because the CPU doesn't have so many cache misses (where it has to wait for the array data to come from the RAM chips). It would be interesting for you to adjust the size of the arrays continually so that you exceed the sizes of the level 1 cache (L1), and then the level 2 cache (L2), of your CPU and plot the time taken for your code to execute against the sizes of the arrays. The graph shouldn't be a straight line like you'd expect.
Give your ul
an id
,
<ul id='yourUlId' class="subforums" style="display: none; overflow-x: visible; overflow-y: visible; ">
then do
var yourUl = document.getElementById("yourUlId");
yourUl.style.display = yourUl.style.display === 'none' ? '' : 'none';
IF you're using jQuery, this becomes:
var $yourUl = $("#yourUlId");
$yourUl.css("display", $yourUl.css("display") === 'none' ? '' : 'none');
Finally, you specifically said that you wanted to manipulate this css property, and not simply show or hide the underlying element. Nonetheless I'll mention that with jQuery
$("#yourUlId").toggle();
will alternate between showing or hiding this element.
You have 3 options to edit commits in Mercurial:
hg strip --keep --rev -1
undo the last (1) commit(s), so you can do it again (see this answer for more information).
Using the MQ extension, which is shipped with Mercurial
Even if it isn't shipped with Mercurial, the Histedit extension is worth mentioning
You can also have a look on the Editing History page of the Mercurial wiki.
In short, editing history is really hard and discouraged. And if you've already pushed your changes, there's barely nothing you can do, except if you have total control of all the other clones.
I'm not really familiar with the git commit --amend
command, but AFAIK, Histedit is what seems to be the closest approach, but sadly it isn't shipped with Mercurial. MQ is really complicated to use, but you can do nearly anything with it.
There's no need for the outer try in your example, so you can at least go down from 3 to 2, and also you don't need closing ;
at the end of the resource list. The advantage of using two try blocks is that all of your code is present up front so you don't have to refer to a separate method:
public List<User> getUser(int userId) {
String sql = "SELECT id, username FROM users WHERE id = ?";
List<User> users = new ArrayList<>();
try (Connection con = DriverManager.getConnection(myConnectionURL);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, userId);
try (ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
users.add(new User(rs.getInt("id"), rs.getString("name")));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
Easy and simple. You don't need create a new FormData or do an Ajax to send image. You can put dragged files in your input field.
$dropzone.ondrop = function (e) {
e.preventDefault();
input.files = e.dataTransfer.files;
}
var $dropzone = document.querySelector('.dropzone');
var input = document.getElementById('file-upload');
$dropzone.ondragover = function (e) {
e.preventDefault();
this.classList.add('dragover');
};
$dropzone.ondragleave = function (e) {
e.preventDefault();
this.classList.remove('dragover');
};
$dropzone.ondrop = function (e) {
e.preventDefault();
this.classList.remove('dragover');
input.files = e.dataTransfer.files;
}
_x000D_
.dropzone {
padding: 10px;
border: 1px dashed black;
}
.dropzone.dragover {
background-color: rgba(0, 0, 0, .3);
}
_x000D_
<div class="dropzone">Drop here</div>
<input type="file" id="file-upload" style="display:none;">
_x000D_
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
Swift 3, 4 & 5
Running code on the main thread
DispatchQueue.main.async {
// Your code here
}
Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N
for the S/U and U/S contention, as in No Conflict.
As for the HOLDLOCK hint the documentation states:
HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.
...
SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...
and the Transaction Isolation Level topic explains what SERIALIZABLE means:
No other transactions can modify data that has been read by the current transaction until the current transaction completes.
Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.
Therefore the behavior you see is perfectly explained by the product documentation:
SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...
After OP edit:
I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.
The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.
As paxdiablo said make -f pax.mk
would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.
Also you can just type make
if your file name is makefile/Makefile
.
Suppose you have two files named makefile
and Makefile
in the same directory then makefile
is executed if make
alone is given. You can even pass arguments to makefile.
Check out more about makefile at this Tutorial : Basic understanding of Makefile
I am experiencing the same issue.. and I build some logging into several functions that I could identify that were frequently running long. when I say frequently I mean about 2% of the time. So part of the log inserted the start time and the end time of the procedure or query. I then produced a simple report sorting several days of logs by the total execution time descending. here is what I found.
the long running instances always started between HH:00 and HH:02 or HH:30 an HH:32 and none of the short running queries ran between those times. Interesting....
Now It seems that there is actually more order to the chaos that I was experiencing. I was using a recovery target of 0 this implemented "indirect checkpoints" in my databases so that my recovery time could be achieved at nearly 1 minute. causing these checkpoints to be created every 30 mins.
WOW, what a coincidence!
In Microsoft's online documentation about changing the recovery time of a database comes with this little warning...
"An online transactional workload on a database that is configured for indirect checkpoints could experience performance degradation."
Wow go figure...
so I modified my recovery time and bango no more issues.
My final solution was to use Python Markdown. I rolled my own extension that fixed the fence blocks.
Problem Cause : The process of the current program is still running without interuption. (This is the reason why you haven't got this issue after a restart)
The fix is simple : Go to cmd and type the command taskkill -im process-name.exe -f
Eg:
taskkill -im demo.exe -f
here,
demo - is my program name
I don't know this particular library, but I've used very similar calls. So this is my best guess:
unsigned char digest[16];
const char* string = "Hello World";
struct MD5Context context;
MD5Init(&context);
MD5Update(&context, string, strlen(string));
MD5Final(digest, &context);
This will give you back an integer representation of the hash. You can then turn this into a hex representation if you want to pass it around as a string.
char md5string[33];
for(int i = 0; i < 16; ++i)
sprintf(&md5string[i*2], "%02x", (unsigned int)digest[i]);
This referes to http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx , http://winrtstoragehelper.codeplex.com/ , Windows 8 app store and .net 4.5
Here is my angle on this:
The async/await language feature makes many things fairly easy but it also introduces a scenario that was rarely encounter before it was so easy to use async calls: reentrance.
This is especially true for event handlers, because for many events you don't have any clue about whats happening after you return from the event handler. One thing that might actually happen is, that the async method you are awaiting in the first event handler, gets called from another event handler still on the same thread.
Here is a real scenario I came across in a windows 8 App store app: My app has two frames: coming into and leaving from a frame I want to load/safe some data to file/storage. OnNavigatedTo/From events are used for the saving and loading. The saving and loading is done by some async utility function (like http://winrtstoragehelper.codeplex.com/). When navigating from frame 1 to frame 2 or in the other direction, the async load and safe operations are called and awaited. The event handlers become async returning void => they cant be awaited.
However, the first file open operation (lets says: inside a save function) of the utility is async too and so the first await returns control to the framework, which sometime later calls the other utility (load) via the second event handler. The load now tries to open the same file and if the file is open by now for the save operation, fails with an ACCESSDENIED exception.
A minimum solution for me is to secure the file access via a using and an AsyncLock.
private static readonly AsyncLock m_lock = new AsyncLock();
...
using (await m_lock.LockAsync())
{
file = await folder.GetFileAsync(fileName);
IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
using (Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result)
{
return (T)serializer.Deserialize(inStream);
}
}
Please note that his lock basically locks down all file operation for the utility with just one lock, which is unnecessarily strong but works fine for my scenario.
Here is my test project: a windows 8 app store app with some test calls for the original version from http://winrtstoragehelper.codeplex.com/ and my modified version that uses the AsyncLock from Stephen Toub http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx.
May I also suggest this link: http://www.hanselman.com/blog/ComparingTwoTechniquesInNETAsynchronousCoordinationPrimitives.aspx
I managed to do it with CSS display: table-*
. I haven't tested with more than 3 blocks though.
v35G
will select everything from the cursor up to line 35.
v
puts you in select mode, 35
specifies the line number that you want to G
go to.
You could also use v}
which will select everything up to the beginning of the next paragraph.
__block is a storage qualifier that can be used in two ways:
Marks that a variable lives in a storage that is shared between the lexical scope of the original variable and any blocks declared within that scope. And clang will generate a struct to represent this variable, and use this struct by reference(not by value).
In MRC, __block can be used to avoid retain object variables a block captures. Careful that this doesn't work for ARC. In ARC, you should use __weak instead.
You can refer to apple doc for detailed information.
I am running MySQL windows with MySQL workbench.
Go to Server > Server status
At the top it says configuration file: "path" (C:\ProgramData\MySQL\...\my.ini
)
Then in the file "my.ini" press control+F and find buffer_pool_size
.
Set the value higher, I would recommend 64 MB (default is 8 MB).
Restart the server by going to Instance>Startup/Shutdown > Stop server (and then later start server again)
In my case I could not delete entries from my table.
Make sure to run 7zip in 'Administrator mode' for extracting to Program Files.
Also, temporarily turning off virus protection worked for some people in the past.
I get the error in another situation, and here are the problem and the solution:
I have 2 classes derived from a same base class named LevledItem:
public partial class Team : LeveledItem
{
//Everything is ok here!
}
public partial class Story : LeveledItem
{
//Everything is ok here!
}
But in their DbContext, I copied some code but forget to change one of the class name:
public class MFCTeamDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Other codes here
modelBuilder.Entity<LeveledItem>()
.Map<Team>(m => m.Requires("Type").HasValue(ItemType.Team));
}
public class ProductBacklogDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Other codes here
modelBuilder.Entity<LeveledItem>()
.Map<Team>(m => m.Requires("Type").HasValue(ItemType.Story));
}
Yes, the second Map< Team> should be Map< Story>. And it cost me half a day to figure it out!
Generally if something works on various computers but fails on only one computer, then there's something wrong with that computer. Here are a few things to check:
(1) Are you running the same stuff on that computer -- OS including patches, etc.
(2) Does the computer report problems? Where to look depends on the OS, but it looks like you're using linux, so check syslog
(3) Run hardware diagnostics, e.g. the ones recommended here. Start with memory and disk checks in particular.
If you can't turn up any issues, then search for a similar issue in the bug parade for whichever VM you're using. Unfortunately if you're already on the latest version of the VM, then you won't necessarily find a fix.
Finally, one more option is simply to try another VM -- e.g. OpenJDK or JRockit, instead of Oracle's standard.
I had same problem. i fixed it. i was using Codeblocks and i save my .cpp file on desktop instead of saving it in Codeblocks file where MinGW is located. So i copied all dll files from MinGW>>bin folder to where my .cpp file was saved.
I Was searching for the same answer, here is what IBM say. IBM Link
POST Creates a new resource. GET Retrieves a resource. PUT Updates an existing resource. DELETE Deletes a resource.
This is totally system dependent. You should experiment to find the optimum solution.
Try starting with bs=8388608
. (As Hitachi HDDs seems to have 8MB cache.)
No, they are not queued, they are sleeping
A lock statement of the form
lock (x) ...
where x is an expression of a reference-type, is precisely equivalent to
var temp = x;
System.Threading.Monitor.Enter(temp);
try { ... }
finally { System.Threading.Monitor.Exit(temp); }
You just need to know that they are waiting to each other, and only one thread will enter to lock block, the others will wait...
Monitor is written fully in .net so it is enough fast, also look at class Monitor with reflector for more details
Yes. You just have to use the RAISE_APPLICATION_ERROR
function. If you also want to name your exception, you'll need to use the EXCEPTION_INIT
pragma in order to associate the error number to the named exception. Something like
SQL> ed
Wrote file afiedt.buf
1 declare
2 ex_custom EXCEPTION;
3 PRAGMA EXCEPTION_INIT( ex_custom, -20001 );
4 begin
5 raise_application_error( -20001, 'This is a custom error' );
6 exception
7 when ex_custom
8 then
9 dbms_output.put_line( sqlerrm );
10* end;
SQL> /
ORA-20001: This is a custom error
PL/SQL procedure successfully completed.
Today i deep in State Design Pattern. I did and tested ThreadState, which equal (+/-) to Threading in C#, as described in picture from Threading in C#
You can easly add new states, configure moves from one state to other is very easy becouse it incapsulated in state implementation
Implementation and using at: Implements .NET ThreadState by State Design Pattern
From the video curse Building .NET Console Applications in C# by Jason Roberts at http://www.pluralsight.com
We could do following to have multiple running process
static void Main(string[] args)
{
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine("Exiting...");
Environment.Exit(0);
};
Console.WriteLine("Press ESC to Exit");
var taskKeys = new Task(ReadKeys);
var taskProcessFiles = new Task(ProcessFiles);
taskKeys.Start();
taskProcessFiles.Start();
var tasks = new[] { taskKeys };
Task.WaitAll(tasks);
}
private static void ProcessFiles()
{
var files = Enumerable.Range(1, 100).Select(n => "File" + n + ".txt");
var taskBusy = new Task(BusyIndicator);
taskBusy.Start();
foreach (var file in files)
{
Thread.Sleep(1000);
Console.WriteLine("Procesing file {0}", file);
}
}
private static void BusyIndicator()
{
var busy = new ConsoleBusyIndicator();
busy.UpdateProgress();
}
private static void ReadKeys()
{
ConsoleKeyInfo key = new ConsoleKeyInfo();
while (!Console.KeyAvailable && key.Key != ConsoleKey.Escape)
{
key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.UpArrow:
Console.WriteLine("UpArrow was pressed");
break;
case ConsoleKey.DownArrow:
Console.WriteLine("DownArrow was pressed");
break;
case ConsoleKey.RightArrow:
Console.WriteLine("RightArrow was pressed");
break;
case ConsoleKey.LeftArrow:
Console.WriteLine("LeftArrow was pressed");
break;
case ConsoleKey.Escape:
break;
default:
if (Console.CapsLock && Console.NumberLock)
{
Console.WriteLine(key.KeyChar);
}
break;
}
}
}
}
internal class ConsoleBusyIndicator
{
int _currentBusySymbol;
public char[] BusySymbols { get; set; }
public ConsoleBusyIndicator()
{
BusySymbols = new[] { '|', '/', '-', '\\' };
}
public void UpdateProgress()
{
while (true)
{
Thread.Sleep(100);
var originalX = Console.CursorLeft;
var originalY = Console.CursorTop;
Console.Write(BusySymbols[_currentBusySymbol]);
_currentBusySymbol++;
if (_currentBusySymbol == BusySymbols.Length)
{
_currentBusySymbol = 0;
}
Console.SetCursorPosition(originalX, originalY);
}
}
The threading.Timer
object (documentation) can count the ten seconds, then get it to set an Event flag indicating that the loop should exit.
The documentation indicates that the timing might not be exact - you'd have to test whether it's accurate enough for your game.
This happens because after updates Android Studio uses API version 23 by default.
The following worked for me:
Press Ctrl + Shift + Alt + S to get to the project structure page. Go to the properties tab and change 23.0.0 to 22.0.1 (or equivalent to what you were using earlier) in the build tool area and rebuild your project.
If that doesn't work, go to gradle:app and then
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.1'
Edit v7:23.0.0 to v7:22.2.1 as shown above and sync gradle. This will definitely work.
The apply
function takes two arguments; the object this
will be binded to, and the arguments, represented with an array.
some_func = function (a, b) { return b }
some_func.apply(obj, ["arguments", "are", "here"])
// "are"
You can try this:
string[] arr = ((IEnumerable)obj).Cast<object>()
.Select(x => x.ToString())
.ToArray();
Once every array implements IEnumerable interface
you can use lst.pop()
or del lst[-1]
pop()
removes and returns the item, in case you don't want have a return use del
It is strange that no one had suggested NIO.2 operations (available since Java 7):
import java.nio.file.{Paths, Files}
import java.nio.charset.StandardCharsets
Files.write(Paths.get("file.txt"), "file contents".getBytes(StandardCharsets.UTF_8))
I think this is by far the simplest and easiest and most idiomatic way, and it does not need any dependencies sans Java itself.
This simple solution posted here Force page refresh on back button worked ...
I've tried to force a page to be downloaded again by browser when user clicks back button, but nothing worked. I appears that modern browsers have separate cache for pages, which stores complete state of a page (including JavaScript generated DOM elements), so when users presses back button, previous page is shown instantly in state the user has left it. If you want to force browser to reload page on back button, add onunload="" to your (X)HTML body element:
<body onunload="">
This disables special cache and forces page reload when user presses back button. Think twice before you use it. Fact of needing such solution is a hint your site navigation concept is flawed.
look here: http://www.tek-tips.com/viewthread.cfm?qid=1209619
arguments.callee.toString();
seems to be right for your needs.
Just addition to above answers ..
[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring
For Ex..
public class GeoPoint
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
[RoutePrefix("api/Values")]
public ValuesController : ApiController
{
[Route("{Latitude}/{Longitude}")]
public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}
Can be called like:
http://localhost/api/values/47.678558/-122.130989
In my testing with Tomcat and Java 8, the JVM was opening an ephemeral port in addition to the one specified for JMX. The following code fixed me up; give it a try if you are having issues where your JMX client (e.g. VisualVM is not connecting.
-Dcom.sun.management.jmxremote.port=8989
-Dcom.sun.management.jmxremote.rmi.port=8989
If you aren't on java 7, you can extract your exception handling to a method - that way you can at least minimize duplication
try {
// try something
}
catch(ExtendsRuntimeException e) { handleError(e); }
catch(Exception e) { handleError(e); }
SELECT col1,
col2
FROM
(SELECT rownum X,col_table1 FROM table1) T1
INNER JOIN
(SELECT rownum Y, col_table2 FROM table2) T2
ON T1.X=T2.Y;
As Johnathan Suggested, you would either want to save it in a cookie or a session.
The easier way would be to use a Session variable.
session_start();
if(!isset($_SESSION['org_referer']))
{
$_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}
Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.
I had this problem. I had to make my class extend ListActivity rather than Activity, and rename my list in the XML to android:id="@android:id/list"
I do just like below, after you set your column AsEnumarable you can sort, order or how you want.
_dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();
The problem is clear: circular dependency between names in entity
and physics
modules.
Regardless of importing the whole module or just a class, the names must be loaded .
Watch this example:
# a.py
import b
def foo():
pass
b.bar()
# b.py
import a
def bar():
pass
a.foo()
This will be compiled into:
# a.py
# import b
# b.py
# import a # ignored, already importing
def bar():
pass
a.foo()
# name a.foo is not defined!!!
# import b done!
def foo():
pass
b.bar()
# done!
With one slight change we can solve this:
# a.py
def foo():
pass
import b
b.bar()
# b.py
def bar():
pass
import a
a.foo()
This will be compiled into:
# a.py
def foo():
pass
# import b
# b.py
def bar():
pass
# import a # ignored, already importing
a.foo()
# import b done!
b.bar()
# done!
And just in case someone's looking for a way to handle this exception and show a meaningful explanation to the user (something like "You're uploading a file that is too big"):
//Global.asax
private void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError();
var httpException = ex as HttpException ?? ex.InnerException as HttpException;
if(httpException == null) return;
if (((System.Web.HttpException)httpException.InnerException).WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
{
//handle the error
Response.Write("Too big a file, dude"); //for example
}
}
(ASP.NET 4 or later required)
def jsonFile = new File('File Path');
JsonSlurper jsonSlurper = new JsonSlurper();
def parseJson = jsonSlurper.parse(jsonFile)
String json = JsonOutput.toJson(parseJson)
def prettyJson = JsonOutput.prettyPrint(json)
println(prettyJson)
Starting from C# 8, you simply can use Range Operator. It's the more efficient and better way to handle such cases.
string AnString = "Hello World!";
AnString = AnString[10..];
I use div instead of tables and am able to target classes within the main class, as below:
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
Use the Chocolatey packet manager. It's a command-line tool similar to npm. Once you have installed it, use
choco install openjdk
in an elevated command prompt to install OpenJDK.
To update an installed version to the latest version, type
choco upgrade openjdk
Pretty simple to use and especially helpful to upgrade to the latest version. No manual fiddling with path environment variables.
Here's the code adopted from the torchvision library:
import urllib
def download_url(url, root, filename=None):
"""Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str, optional): Name to save the file under. If None, use the basename of the URL
"""
root = os.path.expanduser(root)
if not filename:
filename = os.path.basename(url)
fpath = os.path.join(root, filename)
os.makedirs(root, exist_ok=True)
try:
print('Downloading ' + url + ' to ' + fpath)
urllib.request.urlretrieve(url, fpath)
except (urllib.error.URLError, IOError) as e:
if url[:5] == 'https':
url = url.replace('https:', 'http:')
print('Failed download. Trying https -> http instead.'
' Downloading ' + url + ' to ' + fpath)
urllib.request.urlretrieve(url, fpath)
If you are ok to take dependency on torchvision library then you also also simply do:
from torchvision.datasets.utils import download_url
download_url('http://something.com/file.zip', '~/my_folder`)
Trying to make this as short and simple as possible. Creates directory if it doesn't exist, and then returns the desired file:
/** Creates parent directories if necessary. Then returns file */
private static File fileWithDirectoryAssurance(String directory, String filename) {
File dir = new File(directory);
if (!dir.exists()) dir.mkdirs();
return new File(directory + "/" + filename);
}
Inspired by Expire cache on require.js data-main we updated our deploy script with the following ant task:
<target name="deployWebsite">
<untar src="${temp.dir}/website.tar.gz" dest="${website.dir}" compression="gzip" />
<!-- fetch latest buildNumber from build agent -->
<replace file="${website.dir}/js/main.js" token="@Revision@" value="${buildNumber}" />
</target>
Where the beginning of main.js looks like:
require.config({
baseUrl: '/js',
urlArgs: 'bust=@Revision@',
...
});
If you have multiple markers you can use this simple solution to close a previously opened marker when clicking a new marker:
var infowindow = new google.maps.InfoWindow({
maxWidth: (window.innerWidth - 160),
content: content
});
marker.infowindow = infowindow;
var openInfoWindow = '';
marker.addListener('click', function (map, marker) {
if (openInfoWindow) {
openInfoWindow.close();
}
openInfoWindow = this.infowindow;
this.infowindow.open(map, this);
});
Your data types are mismatched when you are retrieving the field values. Check your code and ensure that for each field that you are retrieving that the java object matches that type. For example, retrieving a date into and int. If you are doing a select * then it is possible a change in the fields of the table has happened causing this error to occur. Your SQL should only select the fields you specifically want in order to avoid this error.
Hope this helps.
public List<String> getAllData(String email)
{
db = this.getReadableDatabase();
String[] projection={email};
List<String> list=new ArrayList<>();
Cursor cursor = db.query(TABLE_USER, //Table to query
null, //columns to return
"user_email=?", //columns for the WHERE clause
projection, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null);
// cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(cursor.getColumnIndex("user_id")));
list.add(cursor.getString(cursor.getColumnIndex("user_name")));
list.add(cursor.getString(cursor.getColumnIndex("user_email")));
list.add(cursor.getString(cursor.getColumnIndex("user_password")));
// cursor.moveToNext();
} while (cursor.moveToNext());
}
return list;
}
<=>
(Added in PHP 7)Examples for <=>
Spaceship operator (PHP 7, Source: PHP Manual):
Integers, Floats, Strings, Arrays & objects for Three-way comparison of variables.
// Integers
echo 10 <=> 10; // 0
echo 10 <=> 20; // -1
echo 20 <=> 10; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
// Comparison is case-sensitive
echo "B" <=> "a"; // -1
echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1
// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1
// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0
$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b; // -1
$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 1
// only values are compared
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b; // 1
Generally I face the same problem when I copy some snippets from internet with some special chars that breaks the Intellisense.
It happened a few times with me, I discovered the problem after deleting the file and creating a new one, now when I face the same problem, fist I restart the Visual Studio, if this doesn't resolve the problem, I remove the last snippet I copied from internet and do it by hand, them the problem is gone.
There's nothing built into java to do this. But, hey, java is a programming language, so.. let's program it!
map.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"))
This gives you "param1=12¶m2=cat". Now we need to join the URL and this bit together. You'd think you can just do: URL + "?" + theAbove
but if the URL already contains a question mark, you have to join it all together with "&" instead. One way to check is to see if there's a question mark in the URL someplace already.
Also, I don't quite know what is in your map. If it's raw stuff, you probably have to safeguard the call to e.getKey()
and e.getValue()
with URLEncoder.encode
or similar.
Yet another way to go is that you take a wider view. Are you trying to append a map's content to a URL, or... are you trying to make an HTTP(S) request from a java process with the stuff in the map as (additional) HTTP params? In the latter case, you can look into an http library like OkHttp which has some nice APIs to do this job, then you can forego any need to mess about with that URL in the first place.
This will also work:
import os
import boto
import boto.s3.connection
from boto.s3.key import Key
try:
conn = boto.s3.connect_to_region('us-east-1',
aws_access_key_id = 'AWS-Access-Key',
aws_secret_access_key = 'AWS-Secrete-Key',
# host = 's3-website-us-east-1.amazonaws.com',
# is_secure=True, # uncomment if you are not using ssl
calling_format = boto.s3.connection.OrdinaryCallingFormat(),
)
bucket = conn.get_bucket('YourBucketName')
key_name = 'FileToUpload'
path = 'images/holiday' #Directory Under which file should get upload
full_key_name = os.path.join(path, key_name)
k = bucket.new_key(full_key_name)
k.set_contents_from_filename(key_name)
except Exception,e:
print str(e)
print "error"
If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.
I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.
A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.
If someone is using bootstrap sass note the code is on the _reboot.scss file like this:
button:focus {
outline: 1px dotted;
outline: 5px auto -webkit-focus-ring-color;
}
So if you want to keep the _reboot file I guess feel free to override with plain css instead of trying to look for a variable to change.
i it integer, int to Integer
Integer intObj = new Integer(i);
add to collection
list.add(String.valueOf(intObj));
check correctly if you had ON your virtual env of your peoject, if it's OFF then make it ON. execute following cammands:
workon <your_env_name>
python manage.py runserver
It's working for me
terminal output:
ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}'
file output:
ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' > test.txt
terminal + file output:
ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' | tee test.txt
file output background:
nohup ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' > test.txt &
Floats don't have a height so the containing div has a height of zero.
<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>
overflow:hidden clears the float for most browsers.
zoom:1 clears the float for IE.
Well, both are very, very very very misunderstood and also two completely different things. that aren't mutually exclusive.
Static types are a restriction of the grammar of the language. Statically typed languages strictly could be said to not be context free. The simple truth is that it becomes inconvenient to express a language sanely in context free grammars that doesn't treat all its data simply as bit vectors. Static type systems are part of the grammar of the language if any, they simply restrict it more than a context free grammar could, grammatical checks thus happen in two passes over the source really. Static types correspond to the mathematical notion of type theory, type theory in mathematics simply restricts the legality of some expressions. Like, I can't say 3 + [4,7]
in maths, this is because of the type theory of it.
Static types are thus not a way to 'prevent errors' from a theoretical perspective, they are a limitation of the grammar. Indeed, provided that +, 3 and intervals have the usual set theoretical definitions, if we remove the type system 3 + [4,7]
has a pretty well defined result that's a set. 'runtime type errors' theoretically do not exist, the type system's practical use is to prevent operations that to human beings would make no sense. Operations are still just the shifting and manipulation of bits of course.
The catch to this is that a type system can't decide if such operations are going to occur or not if it would be allowed to run. As in, exactly partition the set of all possible programs in those that are going to have a 'type error', and those that aren't. It can do only two things:
1: prove that type errors are going to occur in a program
2: prove that they aren't going to occur in a program
This might seem like I'm contradicting myself. But what a C or Java type checker does is it rejects a program as 'ungrammatical', or as it calls it 'type error' if it can't succeed at 2. It can't prove they aren't going to occur, that doesn't mean that they aren't going to occur, it just means it can't prove it. It might very well be that a program which will not have a type error is rejected simply because it can't be proven by the compiler. A simple example being if(1) a = 3; else a = "string";
, surely since it's always true, the else-branch will never be executed in the program, and no type error shall occur. But it can't prove these cases in a general way, so it's rejected. This is the major weakness of a lot of statically typed languages, in protecting you against yourself, you're necessarily also protected in cases you don't need it.
But, contrary to popular believe, there are also statically typed languages that work by principle 1. They simply reject all programs of which they can prove it's going to cause a type error, and pass all programs of which they can't. So it's possible they allow programs which have type errors in them, a good example being Typed Racket, it's hybrid between dynamic and static typing. And some would argue that you get the best of both worlds in this system.
Another advantage of static typing is that types are known at compile time, and thus the compiler can use this. If we in Java do "string" + "string"
or 3 + 3
, both +
tokens in text in the end represent a completely different operation and datum, the compiler knows which to choose from the types alone.
Now, I'm going to make a very controversial statement here but bear with me: 'dynamic typing' does not exist.
Sounds very controversial, but it's true, dynamically typed languages are from a theoretical perspective untyped. They are just statically typed languages with only one type. Or simply put, they are languages that are indeed grammatically generated by a context free grammar in practice.
Why don't they have types? Because every operation is defined and allowed on every operant, what's a 'runtime type error' exactly? It's from a theoretical example purely a side-effect. If doing print("string")
which prints a string is an operation, then so is length(3)
, the former has the side effect of writing string
to the standard output, the latter simply error: function 'length' expects array as argument.
, that's it. There is from a theoretical perspective no such thing as a dynamically typed language. They are untyped
All right, the obvious advantage of 'dynamically typed' language is expressive power, a type system is nothing but a limitation of expressive power. And in general, languages with a type system indeed would have a defined result for all those operations that are not allowed if the type system was just ignored, the results would just not make sense to humans. Many languages lose their Turing completeness after applying a type system.
The obvious disadvantage is the fact that operations can occur which would produce results which are nonsensical to humans. To guard against this, dynamically typed languages typically redefine those operations, rather than producing that nonsensical result they redefine it to having the side effect of writing out an error, and possibly halting the program altogether. This is not an 'error' at all, in fact, the language specification usually implies this, this is as much behaviour of the language as printing a string from a theoretical perspective. Type systems thus force the programmer to reason about the flow of the code to make sure that this doesn't happen. Or indeed, reason so that it does happen can also be handy in some points for debugging, showing that it's not an 'error' at all but a well defined property of the language. In effect, the single remnant of 'dynamic typing' that most languages have is guarding against a division by zero. This is what dynamic typing is, there are no types, there are no more types than that zero is a different type than all the other numbers. What people call a 'type' is just another property of a datum, like the length of an array, or the first character of a string. And many dynamically typed languages also allow you to write out things like "error: the first character of this string should be a 'z'"
.
Another thing is that dynamically typed languages have the type available at runtime and usually can check it and deal with it and decide from it. Of course, in theory it's no different than accessing the first char of an array and seeing what it is. In fact, you can make your own dynamic C, just use only one type like long long int and use the first 8 bits of it to store your 'type' in and write functions accordingly that check for it and perform float or integer addition. You have a statically typed language with one type, or a dynamic language.
In practise this all shows, statically typed languages are generally used in the context of writing commercial software, whereas dynamically typed languages tend to be used in the context of solving some problems and automating some tasks. Writing code in statically typed languages simply takes long and is cumbersome because you can't do things which you know are going to turn out okay but the type system still protects you against yourself for errors you don't make. Many coders don't even realize that they do this because it's in their system but when you code in static languages, you often work around the fact that the type system won't let you do things that can't go wrong, because it can't prove it won't go wrong.
As I noted, 'statically typed' in general means case 2, guilty until proven innocent. But some languages, which do not derive their type system from type theory at all use rule 1: Innocent until proven guilty, which might be the ideal hybrid. So, maybe Typed Racket is for you.
Also, well, for a more absurd and extreme example, I'm currently implementing a language where 'types' are truly the first character of an array, they are data, data of the 'type', 'type', which is itself a type and datum, the only datum which has itself as a type. Types are not finite or bounded statically but new types may be generated based on runtime information.
I have used this approach,
What i want is, A layout
always in bottom but whenever Keyboard pops-up that layout
also comes over it
body: Container(
color: Colors.amber,
height: double.maxFinite,
child: new Stack(
//alignment:new Alignment(x, y)
children: <Widget>[
new Positioned(
child: myWidget(context, data.iconName, Colors.red),
),
new Positioned(
child: new Align(
alignment: FractionalOffset.bottomCenter,
child: myWidget(context, data.iconName, Colors.green)
),
)
],
),
),
Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:
char buffer [33];
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
Here's the origin:
It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.
Sometimes this can also happen when you have a stored procedure being called with parameters. For example, if you type something like:
set @runProc = 'dbo.StoredProcedure'
exec @runProc
This will work, However:
set @runProc = 'dbo.StoredProcedure ''foods'''
exec @runProc
This will throw the error "could not find stored procedure dbo.StoredProcedure 'foods'", however this can easily be overcome with parantheses like so:
set @runProc = 'exec dbo.StoredProcedure ''foods'''
exec (@runProc)
Take a look at svnmerge.py. It's command-line, can't be invoked by TortoiseSVN, but it's more powerful. From the FAQ:
Traditional subversion will let you merge changes, but it doesn't "remember" what you've already merged. It also doesn't provide a convenient way to exclude a change set from being merged. svnmerge.py automates some of the work, and simplifies it. Svnmerge also creates a commit message with the log messages from all of the things it merged.
If you have trouble viewing the .env file or it is not showing up in the project just do this: ls -a
.
This allows to see the hidden files in Linux. You can also open the folder with Visual Studio Code and you will see the files and be able to modify them.
This is some really cool stuff! I needed pretty much the same, but with horizontal gradient from white to transparent. And it is working just fine! Here ist my code:
.gradient{
/* webkit example */
background-image: -webkit-gradient(
linear, right top, left top, from(rgba(255, 255, 255, 1.0)),
to(rgba(255, 255, 255, 0))
);
/* mozilla example - FF3.6+ */
background-image: -moz-linear-gradient(
right center,
rgba(255, 255, 255, 1.0) 20%, rgba(255, 255, 255, 0) 95%
);
/* IE 5.5 - 7 */
filter: progid:DXImageTransform.Microsoft.gradient(
gradientType=1, startColor=0, endColorStr=#FFFFFF
);
/* IE8 uses -ms-filter for whatever reason... */
-ms-filter: progid:DXImageTransform.Microsoft.gradient(
gradientType=1, startColor=0, endColoStr=#FFFFFF
);
}
What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon
In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.
To untrack a single file that has already been added/initialized to your repository, i.e., stop tracking the file but not delete it from your system use: git rm --cached filename
To untrack every file that is now in your .gitignore
:
First commit any outstanding code changes, and then, run this command:
git rm -r --cached .
This removes any changed files from the index(staging area), then just run:
git add .
Commit it:
git commit -m ".gitignore is now working"
Not a tooltip solution but an adequate workaround:
Start typing the UDF =MyUDF(
then press CTRL + Shift + A and your function parameters will be displayed. So long as those parameters have meaningful names you at-least have a viable prompt
For example, this:
=MyUDF(
+ CTRL + Shift + A
Turns into this:
=MyUDF(sPath, sFileName)
To switch to root so that all subsequent commands are executed with high privileges instead of using sudo
before each command use following command and then provide the password when prompted.
sudo -i
User will change and remain root until you close the terminal. Execute exit
commmand which will change the user back to original user without closing terminal.
All you need is System.Environment.Exit(1);
And it uses the system namespace "using System" that's pretty much always there when you start a project.
You can simply use setKeepScreenOn()
from the View class.
When using JetBrains IDE's with Git, "stashing and unstashing actions are supported in addition to shelving and unshelving. These features have much in common; the major difference is in the way patches are generated and applied. Shelve can operate with either individual files or bunch of files, while Stash can only operate with a whole bunch of changed files at once. Here are some more details on the differences between them."
You can iterate over the CheckedItems
property:
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
MyCompanyClass company = (MyCompanyClass)itemChecked;
MessageBox.Show("ID: \"" + company.ID.ToString());
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkeditems.aspx
I tried to require a development branch from a different repository and not the latest version and I had the same issue and non of the above worked for me :(
after a while I saw in the documentation that in cases of dev branch you need to require with a 'dev-' prefix to the version and the following worked perfectly.
composer require [vendorName]/[packageName]:dev-[gitBranchName]
Regarding Phil Street's post:
It may actually be installed in your 32-bit program folder instead of your default x64, if you're running 64-bit OS. Check to see where 7-zip
is installed, and if it is in Program Files (x86)
then try using this instead:
PATH=%PATH%;C:\Program Files (x86)\7-Zip
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
A workaround, if you want it to be absolutely silent, is to redirect the output to a file (and optionally delete it later).
Robocopy src dest > output.log
del output.log
Click Tools > Firebase to open the Assistant window.
Click to expand one of the listed features (for example, Analytics), then click the provided tutorial link (for example, Log an Analytics event).
Click the Connect to Firebase button to connect to Firebase and add the necessary code to your app.
I have tried "adb kill-server" and restarted Eclipse too many times. I even rebooted my computer. They don't work.
Finally, I turned off test mode of my phone and turned on again. Then everything looked fine.
The best method is trimws().
The following code will apply this function to the entire dataframe.
mydataframe<- data.frame(lapply(mydataframe, trimws),stringsAsFactors = FALSE)
Try -
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
var newDate = new Date(form.startDate.value);
var formattedDate = monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear();
In case you have trouble building boost or prefer not to do that, an alternative is to download the lib files from SourceForge. The link will take you to a folder of zipped lib and dll files for version 1.51. But, you should be able to edit the link to specify the version of choice. Apparently the installer from BoostPro has some issues.
Long.MAX_VALUE
is 9,223,372,036,854,775,807
.
If you were executing your function once per nanosecond, it would still take over 292 years to encounter this situation according to this source.
When that happens, it'll just wrap around to Long.MIN_VALUE
, or -9,223,372,036,854,775,808
as others have said.
The "nsinit" way is:
install nsinit
git clone [email protected]:dotcloud/docker.git
cd docker
make shell
from inside the container:
go install github.com/dotcloud/docker/pkg/libcontainer/nsinit/nsinit
from outside:
docker cp id_docker_container:/go/bin/nsinit /root/
use it
cd /var/lib/docker/execdriver/native/<container_id>/
nsinit exec bash
Along with the SHA-1 id of the commit, date and time of the server time would have helped?
Something like this:
commit happened at 11:30:25 on 19 aug 2013 would show as 6886bbb7be18e63fc4be68ba41917b48f02e09d7_19aug2013_113025
/
(?:
(?<month> (?&mon_29)) [\/] (?<day>(?&day_29))
| (?<month> (?&mon_30)) [\/] (?<day>(?&day_30))
| (?<month> (?&mon_31)) [\/] (?<day>(?&day_31))
)
[\/]
(?<year> [0-9]{4})
(?(DEFINE)
(?<mon_29> 0?2 )
(?<mon_30> 0?[469] | (11) )
(?<mon_31> 0?[13578] | 1[02] )
(?<day_29> 0?[1-9] | [1-2]?[0-9] )
(?<day_30> 0?[1-9] | [1-2]?[0-9] | 30 )
(?<day_31> 0?[1-9] | [1-2]?[0-9] | 3[01] )
)
/x
You can retrieve the elements by name in this version.
say "Month=$+{month} Day=$+{day} Year=$+{year}";
( No attempt has been made to restrict the values for the year. )
You can use
filter: brightness(0) invert(1);
html {_x000D_
background: red;_x000D_
}_x000D_
p {_x000D_
float: left;_x000D_
max-width: 50%;_x000D_
text-align: center;_x000D_
}_x000D_
img {_x000D_
display: block;_x000D_
max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
-webkit-filter: brightness(0) invert(1);_x000D_
filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
Original:_x000D_
<img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
Filter:_x000D_
<img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
First, brightness(0)
makes all image black, except transparent parts, which remain transparent.
Then, invert(1)
makes the black parts white.
Use of javafx.util.Pair is sufficient for most simple Key-Value pairings of any two types that can be instantiated.
Pair<Integer, String> myPair = new Pair<>(7, "Seven");
Integer key = myPair.getKey();
String value = myPair.getValue();
As of Python 3.5, you can use enhanced generators for async functions.
import asyncio
import datetime
Enhanced generator syntax:
@asyncio.coroutine
def display_date(loop):
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
yield from asyncio.sleep(1)
loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()
New async/await
syntax:
async def display_date(loop):
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()
Do this:
date('Y-m-d', strtotime('dd/mm/yyyy'));
But make sure 'dd/mm/yyyy' is the actual date.
Similar issue where I was getting permissions failed. On my setup, I SSH in only. So What I did to correct the issue was
sudo MySQL
SELECT User, Host FROM mysql.user WHERE Host <> '%';
MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User | Host |
+-------+-------------+
| root | 169.254.0.% |
| foo | 192.168.0.% |
| bar | 192.168.0.% |
+-------+-------------+
4 rows in set (0.00 sec)
I need these users moved to 'localhost'. So I issued the following:
UPDATE mysql.user SET host = 'localhost' WHERE user = 'foo';
UPDATE mysql.user SET host = 'localhost' WHERE user = 'bar';
Run SELECT User, Host FROM mysql.user WHERE Host <> '%'; again and we see:
MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User | Host |
+-------+-------------+
| root | 169.254.0.% |
| foo | localhost |
| bar | localhost |
+-------+-------------+
4 rows in set (0.00 sec)
And then I was able to work normally again. Hope that helps someone.
$ mysql -u foo -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 74
Server version: 10.1.23-MariaDB-9+deb9u1 Raspbian 9.0
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
Never mind, I figured it out - I used the Set()
method on Header()
(doh!)
My handler looks like this now:
func saveHandler(w http.ResponseWriter, r *http.Request) {
// allow cross domain AJAX requests
w.Header().Set("Access-Control-Allow-Origin", "*")
}
Maybe this will help someone as caffeine deprived as myself sometime :)
using sizeof()
char h[] = "hello";
printf("%d\n",sizeof(h)-1); //Output = 5
using string.h
#include <string.h>
char h[] = "hello";
printf("%d\n",strlen(h)); //Output = 5
using function (
strlen
implementation)
int strsize(const char* str);
int main(){
char h[] = "hello";
printf("%d\n",strsize(h)); //Output = 5
return 0;
}
int strsize(const char* str){
return (*str) ? strsize(++str) + 1 : 0;
}
the recommended solution in the comments on the OpenSUSE distro suggests to change:
Defaults env_reset
to:
Defaults !env_reset
and then presumably to comment out the following line which isn't needed:
Defaults env_keep = "LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION LC_MEASURE MENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE LC_TIME LC_ALL L ANGUAGE LINGUAS XDG_SESSION_COOKIE"
Easiest way is use read only attribute to prevent direct user input:
<input class="datepicker" type="text" name="date" value="" readonly />
Or you could use HTML5 validation based on pattern attribute. Date input pattern (dd/mm/yyyy or mm/dd/yyyy):
<input type="text" pattern="\d{1,2}/\d{1,2}/\d{4}" class="datepicker" name="date" value="" />
In Notepad++, go to Run ? Run..., select the path and idle.py
file of your Python installation:
C:\Python27\Lib\idlelib\idle.py
add a space and this:
"$(FULL_CURRENT_PATH)"
and here you are!
Video demostration:
protected static $_instance;
public static function getInstance()
{
if(is_null(self::$_instance))
{
self::$_instance = new self();
}
return self::$_instance;
}
This code can apply for any class without caring about its class name.
I see this nice tutorial on how to get the like count from facebook using PHP.
public static function get_the_fb_like( $url = '' ){
$pageURL = 'http://nextopics.com';
$url = ($url == '' ) ? $pageURL : $url; // setting a value in $url variable
$params = 'select comment_count, share_count, like_count from link_stat where url = "'.$url.'"';
$component = urlencode( $params );
$url = 'http://graph.facebook.com/fql?q='.$component;
$fbLIkeAndSahre = json_decode( $this->file_get_content_curl( $url ) );
$getFbStatus = $fbLIkeAndSahre->data['0'];
return $getFbStatus->like_count;
}
here is a sample code.. I don't know how to paste the code with correct format in here, so just kindly visit this link for better view of the code.
/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
int result = 0;
Iterator<Row> rowIterator = xssfSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Cell> cells = new ArrayList<>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cells.add(cellIterator.next());
}
for (int i = cells.size(); i >= 0; i--) {
Cell cell = cells.get(i-1);
if (cell.toString().trim().isEmpty()) {
cells.remove(i-1);
} else {
result = cells.size() > result ? cells.size() : result;
break;
}
}
}
return result;
}
In this case, you can add the query page
and/ or limit
to your URL as a query string.
For example:
?page=0&limit=25 // this would be added onto your URL: http:localhost:5000?page=0&limit=25
Since it would be a String
we need to convert it to a Number
for our calculations. Let's do it using the parseInt
method and let's also provide some default values.
const pageOptions = {
page: parseInt(req.query.page, 10) || 0,
limit: parseInt(req.query.limit, 10) || 10
}
sexyModel.find()
.skip(pageOptions.page * pageOptions.limit)
.limit(pageOptions.limit)
.exec(function (err, doc) {
if(err) { res.status(500).json(err); return; };
res.status(200).json(doc);
});
BTW
Pagination starts with 0
Old question but for a simple API and light-weight solution; you can use perfy which uses high-resolution real time (process.hrtime
) internally.
var perfy = require('perfy');
function end(label) {
return function (err, saved) {
console.log(err ? 'Error' : 'Saved');
console.log( perfy.end(label).time ); // <——— result: seconds.milliseconds
};
}
for (var i = 1; i < LIMIT; i++) {
var label = 'db-save-' + i;
perfy.start(label); // <——— start and mark time
db.users.save({ id: i, name: 'MongoUser [' + i + ']' }, end(label));
}
Note that each time perfy.end(label)
is called, that instance is auto-destroyed.
Disclosure: Wrote this module, inspired by D.Deriso's answer. Docs here.
I had such problem with storage json-string in MySQL. Don't really know why, but using htmlspecialchars_decode berofe json_decode resolved problem.
In addition to the above answers ; After executing the below command
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'
If you get an error as :
[ERROR] Column count of mysql.user is wrong. Expected 42, found 44. The table is probably corrupted
Then try in the cmd as admin; set the path to MySQL server bin folder in the cmd
set path=%PATH%;D:\xampp\mysql\bin;
and then run the command :
mysql_upgrade --force -uroot -p
This should update the server and the system tables.
Then you should be able to successfully run the below commands in a Query in the Workbench :
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'
then remember to execute the following command:
flush privileges;
After all these steps should be able to successfully connect to your MySQL database. Hope this helps...
If you do not care about tick shifting (depending on how long did it took previously on each execution) and you do not want to use channels, it's possible to use native range function.
i.e.
package main
import "fmt"
import "time"
func main() {
go heartBeat()
time.Sleep(time.Second * 5)
}
func heartBeat() {
for range time.Tick(time.Second * 1) {
fmt.Println("Foo")
}
}
If SelectionUnit="Cell"
try this:
string cellValue = GetSelectedCellValue();
Where:
public string GetSelectedCellValue()
{
DataGridCellInfo cellInfo = MyDataGrid.SelectedCells[0];
if (cellInfo == null) return null;
DataGridBoundColumn column = cellInfo.Column as DataGridBoundColumn;
if (column == null) return null;
FrameworkElement element = new FrameworkElement() { DataContext = cellInfo.Item };
BindingOperations.SetBinding(element, TagProperty, column.Binding);
return element.Tag.ToString();
}
Seems like it shouldn't be that complicated, I know...
Edit: This doesn't seem to work on DataGridTemplateColumn
type columns. You could also try this if your rows are made up of a custom class and you've assigned a sort member path:
public string GetSelectedCellValue()
{
DataGridCellInfo cells = MyDataGrid.SelectedCells[0];
YourRowClass item = cells.Item as YourRowClass;
string columnName = cells.Column.SortMemberPath;
if (item == null || columnName == null) return null;
object result = item.GetType().GetProperty(columnName).GetValue(item, null);
if (result == null) return null;
return result.ToString();
}
The answer is very simple. write the below code
import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Import this, and write at the top of your .ts file
import { HostListener } from "@angular/core";
@Component({
selector: "app-login",
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, OnDestroy {
// Declare height and width variables
scrHeight:any;
scrWidth:any;
@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
this.scrHeight = window.innerHeight;
this.scrWidth = window.innerWidth;
console.log(this.scrHeight, this.scrWidth);
}
// Constructor
constructor() {
this.getScreenSize();
}
}
Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
df['col'] = 'str' + df['col'].astype(str)
Example:
>>> df = pd.DataFrame({'col':['a',0]})
>>> df
col
0 a
1 0
>>> df['col'] = 'str' + df['col'].astype(str)
>>> df
col
0 stra
1 str0
I just had this error, I was calling dr.NextResult()
instead of dr.Read()
.
I'm using the following trick to stop HTML5 video. pause() the video on modal close and set currentTime = 0;
<script>
var video = document.getElementById("myVideoPlayer");
function stopVideo(){
video.pause();
video.currentTime = 0;
}
</script>
Now you can use stopVideo() method to stop HTML5 video. Like,
$("#stop").on('click', function(){
stopVideo();
});
Quoted from PEP 343 -- The "with" Statement (added import statement):
Redirect stdout temporarily:
import sys
from contextlib import contextmanager
@contextmanager
def stdout_redirected(new_stdout):
save_stdout = sys.stdout
sys.stdout = new_stdout
try:
yield None
finally:
sys.stdout = save_stdout
Used as follows:
with open(filename, "w") as f:
with stdout_redirected(f):
print "Hello world"
This isn't thread-safe, of course, but neither is doing this same dance manually. In single-threaded programs (for example in scripts) it is a popular way of doing things.
Something like this:
$("input[name=test]").is(":checked");
Using the jQuery is() function should work.
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?
Although I would suggest the Apache approach is better, SVN Serve works fine and is pretty straightforward.
Assuming your repository is called "my_repo", and it is stored in C:\svn_repos:
Create a file called "passwd" in "C:\svn_repos\my_repo\conf". This file should look like:
[Users]
username = password
john = johns_password
steve = steves_password
In C:\svn_repos\my_repo\conf\svnserve.conf set:
[general]
password-db = passwd
auth-access=read
auth-access=write
This will force users to log in to read or write to this repository.
Follow these steps for each repository, only including the appropriate users in the passwd
file for each repository.
<?php $data = "<div><p>Welcome to my PHP class, we are glad you are here</p></div>"; echo strip_tags($data); ?>
Or if you have a content coming from the database;
<?php $data = strip_tags($get_row['description']); ?>
<?=substr($data, 0, 100) ?><?php if(strlen($data) > 100) { ?>...<?php } ?>
First you need an object
public class MyObject {
public string Id {get;set;}
public string Text {get;set;}
...
}
Then in here
using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {
using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
}
}
I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.
JavaScriptSerializer System.Web.Script.Serialization
Many times when producing HTML email blasts you cannot use style sheets or style /style blocks. All CSS needs to be inline. In the case where you want to adjust the spacing between the bullets I use li style="margin-bottom:8px;" in each bullet item. Customize the pixels value to your liking.
Shared Preferences are the key/value pairs that we can store. They are internal type of storage which means we do not have to create an external database to store it. To see it go to, 1) Go to View in the menu bar. Select Tool Windows. 2) Click on Device File Explorer. 3) Device File Explorer opens up in the right hand side. 4) Find the data folder and click on it. 5) In the data folder, you can select another data folder. 6) Try to search for your package name in this data folder. Ex: com.example.com 7) Then Click on shared_prefs and open the .xml file.
Hope this helps!
I spent quite a bit of time also looking to launch a simple Python program at 01:00. For some reason, I couldn't get cron to launch it and APScheduler seemed rather complex for something that should be simple. Schedule (https://pypi.python.org/pypi/schedule) seemed about right.
You will have to install their Python library:
pip install schedule
This is modified from their sample program:
import schedule
import time
def job(t):
print "I'm working...", t
return
schedule.every().day.at("01:00").do(job,'It is 01:00')
while True:
schedule.run_pending()
time.sleep(60) # wait one minute
You will need to put your own function in place of job and run it with nohup, e.g.:
nohup python2.7 MyScheduledProgram.py &
Don't forget to start it again if you reboot.
You must use the column names and then set the values to insert (both ? marks):
//insert 1st row
String inserting = "INSERT INTO employee(emp_name ,emp_address) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.executeUpdate();
Am I missing something?
Yes. ;-)
This phenomenon exists because of the uniform interface constraint. REST likes using already existing standards instead of reinventing the wheel. The HTTP standard has already proven to be highly scalable (the web is working for a while). Why should we fix something which is not broken?!
note: The uniform interface constraint is important if you want to decouple the clients from the service. It is similar to defining interfaces for classes in order to decouple them from each other. Ofc. in here the uniform interface consists of standards like HTTP, MIME types, URI, RDF, linked data vocabs, hydra vocab, etc...
If you are happy with "blah" in somestring
but want it to be a function/method call, you can probably do this
import operator
if not operator.contains(somestring, "blah"):
continue
All operators in Python can be more or less found in the operator module including in
.
The ASPX code will look something like this:
<asp:RadioButtonList ID="rblist1" runat="server">
<asp:ListItem Text ="Item1" Value="1" />
<asp:ListItem Text ="Item2" Value="2" />
<asp:ListItem Text ="Item3" Value="3" />
<asp:ListItem Text ="Item4" Value="4" />
</asp:RadioButtonList>
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />
And the code behind:
protected void Button1_Click(object sender, EventArgs e)
{
string selectedValue = rblist1.SelectedValue;
Response.Write(selectedValue);
}
Adding to the popular answer to include this error:
"ERROR 1200 (HY000): The server is not configured as slave; fix in config file or with CHANGE MASTER TO",
Replication from slave in one shot:
In one terminal window:
mysql -h <Master_IP_Address> -uroot -p
After connecting,
RESET MASTER;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;
The status appears as below: Note that position number varies!
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 | 98 | your_DB | |
+------------------+----------+--------------+------------------+
Export the dump similar to how he described "using another terminal"!
Exit and connect to your own DB(which is the slave):
mysql -u root -p
The type the below commands:
STOP SLAVE;
Import the Dump as mentioned (in another terminal, of course!) and type the below commands:
RESET SLAVE;
CHANGE MASTER TO
MASTER_HOST = 'Master_IP_Address',
MASTER_USER = 'your_Master_user', // usually the "root" user
MASTER_PASSWORD = 'Your_MasterDB_Password',
MASTER_PORT = 3306,
MASTER_LOG_FILE = 'mysql-bin.000001',
MASTER_LOG_POS = 98; // In this case
Once logged, set the server_id parameter (usually, for new / non-replicated DBs, this is not set by default),
set global server_id=4000;
Now, start the slave.
START SLAVE;
SHOW SLAVE STATUS\G;
The output should be the same as he described.
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Note: Once replicated, the master and slave share the same password!
Use Arrays.copyOf my friend.
In my case,
I define the activity twice in manifest file
<application
android:allowBackup="false"
android:label="@string/app_name"
>
<activity
android:name="com.xxx.ActivityOne"
android:configChanges="orientation|screenSize"
android:windowSoftInputMode="stateHidden|adjustResize" />
//Problem here.. same activity twice define
<activity
android:name="com.xxx.ActivityOne"
android:configChanges="orientation|screenSize"
android:windowSoftInputMode="stateHidden|adjustResize" />
</application>
After remove the duplicate error solved.
<form name = "numberForm">
<div>
<input type="number"
placeholder = "Enter your phonenumber"
class = "formcontroll"
name = "numbers"
ng-minlength = "10"
ng-maxlength = "10"
ng-model="phno" required/>
<p ng-show = "numberForm.numbers.$error.required ||
numberForm.numbers.$error.number">
Valid phone number is required</p>
<p ng-show = "((numberForm.numbers.$error.minlength ||
numberForm.numbers.$error.maxlength)
&& numberForm.numbers.$dirty)">
Phone number should be 10 digits</p><br><br>
</div>
</form>
I have a diary class and so i am not writing setting the values again and again
public Diary() {
this.Like = defaultLike;
this.Dislike = defaultDislike;
}
public Diary(string title, string diary): this()
{
this.Title = title;
this.DiaryText = diary;
}
public Diary(string title, string diary, string category): this(title, diary) {
this.Category = category;
}
public Diary(int id, string title, string diary, string category)
: this(title, diary, category)
{
this.DiaryID = id;
}
First of all, android.graphics.Color is a class thats composed of only static methods. How and why did you create a new android.graphics.Color object? (This is completely useless and the object itself stores no data)
But anyways... I'm going to assume your using some object that actually stores data...
A integer is composed of 4 bytes (in java). Looking at the function getRGB() from the standard java Color object we can see java maps each color to one byte of the integer in the order ARGB (Alpha-Red-Green-Blue). We can replicate this behavior with a custom method as follows:
public int getIntFromColor(int Red, int Green, int Blue){
Red = (Red << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
Green = (Green << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
Blue = Blue & 0x000000FF; //Mask out anything not blue.
return 0xFF000000 | Red | Green | Blue; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
}
This assumes you can somehow retrieve the individual red, green and blue colour components and that all the values you passed in for the colours are 0-255.
If your RGB values are in form of a float percentage between 0 and 1 consider the following method:
public int getIntFromColor(float Red, float Green, float Blue){
int R = Math.round(255 * Red);
int G = Math.round(255 * Green);
int B = Math.round(255 * Blue);
R = (R << 16) & 0x00FF0000;
G = (G << 8) & 0x0000FF00;
B = B & 0x000000FF;
return 0xFF000000 | R | G | B;
}
As others have stated, if you're using a standard java object, just use getRGB();
If you decide to use the android color class properly you can also do:
int RGB = android.graphics.Color.argb(255, Red, Green, Blue); //Where Red, Green, Blue are the RGB components. The number 255 is for 100% Alpha
or
int RGB = android.graphics.Color.rgb(Red, Green, Blue); //Where Red, Green, Blue are the RGB components.
as others have stated... (Second function assumes 100% alpha)
Both methods basically do the same thing as the first method created above.
Please run it from the directory where POM.XML resides.
If you are using Xcode 8.0 to 8.3.3 and swift 2.2 to 3.0
In my case need to change in URL http:// to https:// (if not working then try)
Add an App Transport Security Setting: Dictionary.
Add a NSAppTransportSecurity: Dictionary.
Add a NSExceptionDomains: Dictionary.
Add a yourdomain.com: Dictionary. (Ex: stackoverflow.com)
Add Subkey named " NSIncludesSubdomains" as Boolean: YES
Add Subkey named " NSExceptionAllowsInsecureHTTPLoads" as Boolean: YES
Before User Shift + = or Shift - , you have to first set the key map as mentioned below
Have you checked MZTools?? It does a lot of cool stuff...
If I'm not wrong, one of the functionalities it offers is to set your own shortcuts.
You can achieve this using the location
object.
location.href = "http://someurl";
The answer is:
gcc --version
Rather than searching on forums, for any possible option you can always type:
gcc --help
haha! :)
What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.
There is also a shorter form for $(document).ready(function(){...})
in $(function(){...})
.
So, this is all you need:
$(function(){
$('div.easy_editor').css('border','9px solid red');
});
If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:
$(function(){
$('.easy_editor').css('border','9px solid red');
});
You can use the str_replace
when you declare your variable $b like that :
$b = str_replace(" ", "", '88 8888');
echo (int)$b;
Or the most beautiful solution is to use intval :
$b = intval(str_replace(" ", "", '88 8888');
echo $b;
If your value '88 888' is from an other variable, just replace the '88 888' by the variable who contains your String.
You're checking if the result of IndexOf is larger or equal 0, meaning whether the match starts anywhere in the string. Try checking if it's equal to 0:
if (testList.FindAll(x => x.IndexOf(keyword,
StringComparison.OrdinalIgnoreCase) >= 0).Count > 0)
Console.WriteLine("Found in list");
Now "goat" and "oat" won't match, but "goat" and "goa" will. To avoid this, you can compare the lenghts of the two strings.
To avoid all this complication, you can use a dictionary instead of a list. They key would be the lowercase string, and the value would be the real string. This way, performance isn't hurt because you don't have to use ToLower
for each comparison, but you can still use Contains
.
if x
is a vector with raw scores then scale(x)
is a vector with standardized scores.
Or manually: (x-mean(x))/sd(x)
In this case, they are the same. None
is a singleton object (there only ever exists one None
).
is
checks to see if the object is the same object, while == just checks if they are equivalent.
For example:
p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent
But since there is only one None
, they will always be the same, and is
will return True.
p = None
q = None
p is q # True because they are both pointing to the same "None"
You can use collect method to add list of integers.
List<Integer> list = Arrays.asList(2, 4, 5, 6);
int sum = list.stream().collect(Collectors.summingInt(Integer::intValue));
I agree partly with Ed Staub. Gradle definitely is more powerful compared to maven and provides more flexibility long term.
After performing an evaluation to move from maven to gradle, we decided to stick to maven itself for two issues we encountered with gradle ( speed is slower than maven, proxy was not working ) .
MySQL has 4 levels of collation: server, database, table, column. If you change the collation of the server, database or table, you don't change the setting for each column, but you change the default collations.
E.g if you change the default collation of a database, each new table you create in that database will use that collation, and if you change the default collation of a table, each column you create in that table will get that collation.
Simple check can be made. I am currently using Spring MVC architecture along with hibernate. I had missed writing @Controller annotations just above class name. This was causing the problem for me.
@Controller
public class MyClass{
...
}
Hope this simple check solves your problem.
The pyplot functions you are calling, axhline()
and axvline()
draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin
or ymin
use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis.
Instead, use plt.plot((x1, x2), (y1, y2), 'k-')
to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot
.
Try withColumn
with the function when
as follows:
val sqlContext = new SQLContext(sc)
import sqlContext.implicits._ // for `toDF` and $""
import org.apache.spark.sql.functions._ // for `when`
val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
.toDF("A", "B", "C")
val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))
newDf.show()
shows
+---+----+---+---+
| A| B| C| D|
+---+----+---+---+
| 4|blah| 2| 1|
| 2| | 3| 0|
| 56| foo| 3| 1|
|100|null| 5| 0|
+---+----+---+---+
I added the (100, null, 5)
row for testing the isNull
case.
I tried this code with Spark 1.6.0
but as commented in the code of when
, it works on the versions after 1.4.0
.
The type comes after the name in TypeScript, partly because types are optional.
So your line:
HTMLElement el = document.getElementById('content');
Needs to change to:
const el: HTMLElement = document.getElementById('content');
Back in 2013, the type HTMLElement
would have been inferred from the return value of getElementById
, this is still the case if you aren't using strict null checks (but you ought to be using the strict modes in TypeScript). If you are enforcing strict null checks you will find the return type of getElementById
has changed from HTMLElement
to HTMLElement | null
. The change makes the type more correct, because you don't always find an element.
So when using type mode, you will be encouraged by the compiler to use a type assertion to ensure you found an element. Like this:
const el: HTMLElement | null = document.getElementById('content');
if (el) {
const definitelyAnElement: HTMLElement = el;
}
I have included the types to demonstrate what happens when you run the code. The interesting bit is that el
has the narrower type HTMLElement
within the if
statement, due to you eliminating the possibility of it being null.
You can do exactly the same thing, with the same resulting types, without any type annotations. They will be inferred by the compiler, thus saving all that extra typing:
const el = document.getElementById('content');
if (el) {
const definitelyAnElement = el;
}
Save your file in UTF8 format.
Verify the file format using the following (UNIX) command:
file -bi filename.tex
You should see:
text/x-tex; charset=utf-8
Convert the file using iconv
if it is not UTF8:
iconv --from-code=ISO-8859-1 --to-code=UTF-8 filename.txt > filename-utf.txt
Version 4.3.5 Updated Code
Since MultipartEntity
has been deprecated. Please see the code below.
String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);
HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);
if (career != null)
builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());
post.setEntity(builder.build());
try {
responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
// System.out.println("Response from Server ==> " + responseBody);
JSONObject object = new JSONObject(responseBody);
Boolean success = object.optBoolean("success");
String message = object.optString("error");
if (!success) {
responseBody = message;
} else {
responseBody = "success";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
There are MYSQL functions you can use. Like this one that resolves the user:
SELECT USER();
This will return something like root@localhost
so you get the host and the user.
To get the current database run this statement:
SELECT DATABASE();
Other useful functions can be found here: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html
update_attribute
and update_attributes
are similar, but
with one big difference: update_attribute
does not run validations.
Also:
update_attribute
is used to update record with single attribute.
Model.update_attribute(:column_name, column_value1)
update_attributes
is used to update record with multiple attributes.
Model.update_attributes(:column_name1 => column_value1, :column_name2 => column_value2, ...)
These two methods are really easy to confuse given their similar names and works. Therefore, update_attribute
is being removed in favor of update_column
.
Now, in Rails4 you can use Model.update_column(:column_name, column_value)
at the place of Model.update_attribute(:column_name, column_value)
Click here to get more info about update_column
.
If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.
First of all, where you're going wrong is the offset.
It should look more like this...
set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%
If the date was Tue 12/02/2013
then it would display it as 2013/02/12
.
To remove the slashes, the code would look more like
set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%
which would output 20130212
And a hint for doing it in the future, if mydate
equals something like %date:~10,4%%date:~7,2%
or the like, you probably forgot a tilde (~).
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
We could use tidyr::extract()
x <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)
library(tidyr)
extract(tibble(data=x),"data", regex = "^(.*?)\\.(.*?)\\.(.*?)\\.(.*?)$",into = LETTERS[1:4])
#> # A tibble: 13 x 4
#> A B C D
#> <chr> <chr> <chr> <chr>
#> 1 F US CLE V13
#> 2 F US CA6 U13
#> 3 F US CA6 U13
#> 4 F US CA6 U13
#> 5 F US CA6 U13
#> 6 F US CA6 U13
#> 7 F US CA6 U13
#> 8 F US CA6 U13
#> 9 F US DL U13
#> 10 F US DL U13
#> 11 F US DL U13
#> 12 F US DL Z13
#> 13 F US DL Z13
Another option is to use unglue::unglue_data()
# remotes::install_github("moodymudskipper/unglue")
library(unglue)
unglue_data(x,"{A}.{B}.{C}.{D}")
#> A B C D
#> 1 F US CLE V13
#> 2 F US CA6 U13
#> 3 F US CA6 U13
#> 4 F US CA6 U13
#> 5 F US CA6 U13
#> 6 F US CA6 U13
#> 7 F US CA6 U13
#> 8 F US CA6 U13
#> 9 F US DL U13
#> 10 F US DL U13
#> 11 F US DL U13
#> 12 F US DL Z13
#> 13 F US DL Z13
Created on 2019-09-14 by the reprex package (v0.3.0)
(See update at end of answer.)
You can get a NodeList
of all of the input
elements via getElementsByTagName
(DOM specification, MDC, MSDN), then simply loop through it:
var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
There I've used it on the document
, which will search the entire document. It also exists on individual elements (DOM specification), allowing you to search only their descendants rather than the whole document, e.g.:
var container, inputs, index;
// Get the container element
container = document.getElementById('container');
// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
...but you've said you don't want to use the parent form
, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).
Update: getElementsByTagName
is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the input
elements?
That's where the useful querySelectorAll
comes in: It lets us get a list of elements that match any CSS selector we want. So for our checkboxes example:
var checkboxes = document.querySelectorAll("input[type=checkbox]");
You can also use it at the element level. For instance, if we have a div
element in our element
variable, we can find all of the span
s with the class foo
that are inside that div
like this:
var fooSpans = element.querySelectorAll("span.foo");
querySelectorAll
and its cousin querySelector
(which just finds the first matching element instead of giving you a list) are supported by all modern browsers, and also IE8.
Try this
keys = [next(iter(x.keys())) for x in test]
print(list(keys))
The result looks like this. ['foo', 'hello']
You can find more possible solutions here.
I am using a powershell build and couldn't get npm to run without changing the current directory.
Ended up using the start command and just specifying the working directory:
start "npm" -ArgumentList "install --warn" -wo $buildFolder
I was running into the same issue but was able to package all dependencies into my jar file using the Maven Shade Plugin
Make a new div with whatever name (I will just use table-split) and give it a width, without adding content to it, while placing it between necessary divs that need to be separated.
You can add whatever width you find necessary. I just used 0.6% because it's what I needed for when I had to do this.
.table-split {_x000D_
display: table-cell;_x000D_
width: 0.6%_x000D_
}
_x000D_
<div class="table-split"></div>
_x000D_
I would just use the FindAll method on the List class. i.e.:
List<Person> filteredResults =
people.FindAll(p => return !exclusions.Contains(p));
Not sure if the syntax will exactly match your objects, but I think you can see where I'm going with this.
You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:
# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful
On Ubuntu/Debian you can configure headers in the file
/etc/apache2/conf-enabled/security.conf
#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"
#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"
Note: This is the bottom part of the file. Only the last three entries are CSP settings.
The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.
Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.
While you're at it you could take a look at the other header settings and install mod_security
Further reading:
https://developers.google.com/web/fundamentals/security/csp/
Instead of downloading separate java files as suggested by Veer, you could just add this JAR file to your package.
To add the jar file to your project in Eclipse, do the following:
SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).
The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).
for disable sorting on any column in datatable use the following
aoColumnDefs: [{ "aTargets": [ 0 ], "bSortable": false}],
it means "aTargets": [ 0 ]
is the column id starting from 0
so in your case it becomes:
$(".tableSort").dataTable({
aaSorting: [[0, 'asc']],
aoColumnDefs: [
{ "aTargets": [ -1 ], "bSortable": false},
]
});
create table xyz_new as select * from xyz where 1=0;
http://www.codeassists.com/questions/oracle/copy-table-data-to-new-table-in-oracle
Look at this one: Convert List/IEnumerable to DataTable/DataView
In my code I changed it into a extension method:
public static DataTable ToDataTable<T>(this List<T> items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach(var prop in props)
{
tb.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (var item in items)
{
var values = new object[props.Length];
for (var i=0; i<props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}
mcrypt
without the use of port
or brew
Note: these instructions are long because they intend to be thorough. The process is actually fairly straight-forward. If you're an optimist, you can skip down to the building the mcrypt extension section, but you may very well see the errors I did, telling me to install
autoconf
andlibmcrypt
first.
I have just gone through this on a fresh install of OSX 10.9. The solution which worked for me was very close to that of ckm - I am including their steps as well as my own in full, for completeness. My main goal (other than "having mcrypt
") was to perform the installation in a way which left the least impact on the system as a whole. That means doing things manually (no port
, no brew
)
To do things manually, you will first need a couple of dependencies: one for building PHP modules, and another for mcrypt
specifically. These are autoconf
and libmcrypt
, either of which you might have already, but neither of which you will have on a fresh install of OSX 10.9.
Autoconf (for lack of a better description) is used to tell not-quite-disparate, but still very different, systems how to compile things. It allows you to use the same set of basic commands to build modules on Linux as you would on OSX, for example, despite their different file-system hierarchies, etc. I used the method described by Ares on StackOverflow, which I will reproduce here for completeness. This one is very straight-forward:
$ mkdir -p ~/mcrypt/dependencies/autoconf
$ cd ~/mcrypt/dependencies/autoconf
$ curl -OL http://ftpmirror.gnu.org/autoconf/autoconf-latest.tar.gz
$ tar xzf autoconf-latest.tar.gz
$ cd autoconf-*/
$ ./configure --prefix=/usr/local
$ make
$ sudo make install
Next, verify the installation by running:
$ which autoconf
which should return /usr/local/bin/autoconf
Next, you will need libmcrypt
, used to provide the guts of the mcrypt
extension (the extension itself being a provision of a PHP interface into this library). The method I used was based on the one described here, but I have attempted to simplify things as best I can:
First, download the libmcrypt
source, available from SourceForge, and available as of the time of this writing, specifically, at:
http://sourceforge.net/projects/mcrypt/files/Libmcrypt/2.5.8/libmcrypt-2.5.8.tar.bz2/download
You'll need to jump through the standard SourceForge hoops to get at the real download link, but once you have it, you can pass it in to something like this:
$ mkdir -p ~/mcrypt/dependencies/libmcrypt
$ cd ~/mcrypt/dependencies/libmcrypt
$ curl -L -o libmcrypt.tar.bz2 '<SourceForge direct link URL>'
$ tar xjf libmcrypt.tar.bz2
$ cd libmcrypt-*/
$ ./configure
$ make
$ sudo make install
The only way I know of to verify that this has worked is via the ./configure
step for the mcrypt
extension itself (below)
This is our actual goal. Hopefully the brief stint into dependency hell is over now.
First, we're going to need to get the source code for the mcrypt
extension. This is most-readily available buried within the source code for all of PHP. So: determine what version of the PHP source code you need.
$ php --version # to get your PHP version
now, if you're lucky, your current version will be available for download from the main mirrors. If it is, you can type something like:
$ mkdir -p ~/mcrypt/php
$ cd ~/mcrypt/php
$ curl -L -o php-5.4.17.tar.bz2 http://www.php.net/get/php-5.4.17.tar.bz2/from/a/mirror
Unfortunately, my current version (5.4.17, in this case) was not available, so I needed to use the alternative/historical links at http://downloads.php.net/stas/ (also an official PHP download site). For these, you can use something like:
$ mkdir -p ~/mcrypt/php
$ cd ~/mcrypt/php
$ curl -LO http://downloads.php.net/stas/php-5.4.17.tar.bz2
Again, based on your current version.
Once you have it, (and all the dependencies, from above), you can get to the main process of actually building/installing the module.
$ cd ~/mcrypt/php
$ tar xjf php-*.tar.bz2
$ cd php-*/ext/mcrypt
$ phpize
$ ./configure # this is the step which fails without the above dependencies
$ make
$ make test
$ sudo make install
In theory, mcrypt.so
is now in your PHP extension directory. Next, we need to tell PHP about it.
Your php.ini
file needs to be told to load mcrypt
. By default in OSX 10.9, it actually has mcrypt
-specific configuration information, but it doesn't actually activate mcrypt
unless you tell it to.
The php.ini
file does not, by default, exist. Instead, the file /private/etc/php.ini.default
lists the default configuration, and can be used as a good template for creating the "true" php.ini
, if it does not already exist.
To determine whether php.ini
already exists, run:
$ ls /private/etc/php.ini
If there is a result, it already exists, and you should skip the next command.
To create the php.ini
file, run:
$ sudo cp /private/etc/php.ini.default /private/etc/php.ini
Next, you need to add the line:
extension=mcrypt.so
Somewhere in the file. I would recommend searching the file for ;extension=
, and adding it immediately prior to the first occurrence.
Once this is done, the installation and configuration is complete. You can verify that this has worked by running:
php -m | grep mcrypt
Which should output "mcrypt
", and nothing else.
If your use of PHP relies on Apache's httpd
, you will need to restart it before you will notice the changes on the web. You can do so via:
$ sudo apachectl restart
And you're done.
The best way I found so far is to go to the Oauth playground here: https://developers.google.com/oauthplayground/
In the HTTP header for the REST API request, add: "Authorization: Bearer ". Here, Authorization is the key, and "Bearer ". For example: "Authorization: Bearer za29.KluqA3vRtZChWfJDabcdefghijklmnopqrstuvwxyz6nAZ0y6ElzDT3yH3MT5"
VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.
On Error Resume Next
DoStep1
If Err.Number <> 0 Then
WScript.Echo "Error in DoStep1: " & Err.Description
Err.Clear
End If
DoStep2
If Err.Number <> 0 Then
WScript.Echo "Error in DoStop2:" & Err.Description
Err.Clear
End If
'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0
The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.
With little modification but almost similar approach to get the full file path of each sub folder
dataFolderPath = 'UCR_TS_Archive_2015/';
dirData = dir(dataFolderPath); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
fileList = {dirData(~dirIndex).name}'; %'# Get a list of the files
if ~isempty(fileList)
fileList = cellfun(@(x) fullfile(dataFolderPath,x),... %# Prepend path to files
fileList,'UniformOutput',false);
end
subDirs = {dirData(dirIndex).name}; %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'}); %# Find index of subdirectories
%# that are not '.' or '..'
for iDir = find(validIndex) %# Loop over valid subdirectories
nextDir = fullfile(dataFolderPath,subDirs{iDir}); %# Get the subdirectory path
getAllFiles = dir(nextDir);
for k = 1:1:size(getAllFiles,1)
validFileIndex = ~ismember(getAllFiles(k,1).name,{'.','..'});
if(validFileIndex)
filePathComplete = fullfile(nextDir,getAllFiles(k,1).name);
fprintf('The Complete File Path: %s\n', filePathComplete);
end
end
end
If you use an operating system that uses copy-on-write fork()
semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).
The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy
or array
), place that in shared memory, wrap it with multiprocessing.Array
, and pass that to your functions. This answer shows how to do that.
If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing
provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager
proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).
The Manager
approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.
There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing
is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.
In your case, you should simply use
$firstapiOutput->document_number
as the input for the second api.
I have faced the issue "Renaming the folder without loosing history". To fix it, run:
$ git mv oldfolder temp && git mv temp newfolder
$ git commit
$ git push
Try this:
apt-get install lib32stdc++6
For classes that you create (ie. are not part of the Android) its possible to avoid the crash completely.
Any class that implements finalize()
has some unavoidable probability of crashing as explained by @oba. So instead of using finalizers to perform cleanup, use a PhantomReferenceQueue
.
For an example check out the implementation in React Native: https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/jni/DestructorThread.java
Yahoo's api provides a CSV dump:
Example: http://finance.yahoo.com/d/quotes.csv?s=msft&f=price
I'm not sure if it is documented or not, but this code sample should showcase all of the features (namely the stat types [parameter f in the query string]. I'm sure you can find documentation (official or not) if you search for it.
http://www.goldb.org/ystockquote.html
Edit
I found some unofficial documentation:
Do you mean a C string, as in a char*
string, or a C++ std::string
object?
Either way, you use the same constructor, as documented in the QT reference:
For a regular C string, just use the main constructor:
char name[] = "Stack Overflow";
QString qname(name);
For a std::string
, you obtain the char*
to the buffer and pass that to the QString
constructor:
std::string name2("Stack Overflow");
QString qname2(name2.c_str());
You still need to add
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
</plugin>
</plugins>
in your build, because pluginManagement
is only a way to share the same plugin configuration across all your project modules.
From Maven documentation:
pluginManagement: is an element that is seen along side plugins. Plugin Management contains plugin elements in much the same way, except that rather than configuring plugin information for this particular project build, it is intended to configure project builds that inherit from this one. However, this only configures plugins that are actually referenced within the plugins element in the children. The children have every right to override pluginManagement definitions.
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_
Reduce makes this fairly easy:
merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
Here's a fully example using some mock data:
set.seed(1)
list.of.data.frames = list(data.frame(x=1:10, a=1:10), data.frame(x=5:14, b=11:20), data.frame(x=sample(20, 10), y=runif(10)))
merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
tail(merged.data.frame)
# x a b y
#12 12 NA 18 NA
#13 13 NA 19 NA
#14 14 NA 20 0.4976992
#15 15 NA NA 0.7176185
#16 16 NA NA 0.3841037
#17 19 NA NA 0.3800352
And here's an example using these data to replicate my.list
:
merged.data.frame = Reduce(function(...) merge(..., by=match.by, all=T), my.list)
merged.data.frame[, 1:12]
# matchname party st district chamber senate1993 name.x v2.x v3.x v4.x senate1994 name.y
#1 ALGIERE 200 RI 026 S NA <NA> NA NA NA NA <NA>
#2 ALVES 100 RI 019 S NA <NA> NA NA NA NA <NA>
#3 BADEAU 100 RI 032 S NA <NA> NA NA NA NA <NA>
Note: It looks like this is arguably a bug in merge
. The problem is there is no check that adding the suffixes (to handle overlapping non-matching names) actually makes them unique. At a certain point it uses [.data.frame
which does make.unique
the names, causing the rbind
to fail.
# first merge will end up with 'name.x' & 'name.y'
merge(my.list[[1]], my.list[[2]], by=match.by, all=T)
# [1] matchname party st district chamber senate1993 name.x
# [8] votes.year.x senate1994 name.y votes.year.y
#<0 rows> (or 0-length row.names)
# as there is no clash, we retain 'name.x' & 'name.y' and get 'name' again
merge(merge(my.list[[1]], my.list[[2]], by=match.by, all=T), my.list[[3]], by=match.by, all=T)
# [1] matchname party st district chamber senate1993 name.x
# [8] votes.year.x senate1994 name.y votes.year.y senate1995 name votes.year
#<0 rows> (or 0-length row.names)
# the next merge will fail as 'name' will get renamed to a pre-existing field.
Easiest way to fix is to not leave the field renaming for duplicates fields (of which there are many here) up to merge
. Eg:
my.list2 = Map(function(x, i) setNames(x, ifelse(names(x) %in% match.by,
names(x), sprintf('%s.%d', names(x), i))), my.list, seq_along(my.list))
The merge
/Reduce
will then work fine.
A simple searchable goto for the use of commenting out code blocks when debugging.
GOTO=false
if ${GOTO}; then
echo "GOTO failed"
...
fi # End of GOTO
echo "GOTO done"
Result is-> GOTO done
I use MDI quite a lot, I like it much more (where it can be used) than multiple floating forms.
But to get the best from it you need to get to grips with your own events. It makes life so much easier for you.
A skeletal example.
Have your own interupt types,
//Clock, Stock and Accoubts represent the actual forms in
//the MDI application. When I have multiple copies of a form
//I also give them an ID, at the time they are created, then
//include that ID in the Args class.
public enum InteruptSource
{
IS_CLOCK = 0, IS_STOCKS, IS_ACCOUNTS
}
//This particular event type is time based,
//but you can add others to it, such as document
//based.
public enum EVInterupts
{
CI_NEWDAY = 0, CI_NEWMONTH, CI_NEWYEAR, CI_PAYDAY, CI_STOCKPAYOUT,
CI_STOCKIN, DO_NEWEMAIL, DO_SAVETOARCHIVE
}
Then your own Args type
public class ControlArgs
{
//MDI form source
public InteruptSource source { get; set; }
//Interrupt type
public EVInterupts clockInt { get; set; }
//in this case only a date is needed
//but normally I include optional data (as if a C UNION type)
//the form that responds to the event decides if
//the data is for it.
public DateTime date { get; set; }
//CI_STOCKIN
public StockClass inStock { get; set; }
}
Then use the delegate within your namespace, but outside of a class
namespace MyApplication
{
public delegate void StoreHandler(object sender, ControlArgs e);
public partial class Form1 : Form
{
//your main form
}
Now either manually or using the GUI, have the MDIparent respond to the events of the child forms.
But with your owr Args, you can reduce this to a single function. and you can have provision to interupt the interupts, good for debugging, but can be usefull in other ways too.
Just have al of your mdiparent event codes point to the one function,
calendar.Friday += new StoreHandler(MyEvents);
calendar.Saturday += new StoreHandler(MyEvents);
calendar.Sunday += new StoreHandler(MyEvents);
calendar.PayDay += new StoreHandler(MyEvents);
calendar.NewYear += new StoreHandler(MyEvents);
A simple switch mechanism is usually enough to pass events on to appropriate forms.
You need to call srand()
once, to randomize the seed, and then call rand()
in your loop:
#include <stdlib.h>
#include <time.h>
#define size 10
srand(time(NULL)); // randomize seed
for(i=0;i<size;i++)
Arr[i] = rand()%size;
you can use
<a href="\\computername\folder">Open folder</a>
in Internet Explorer
The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:
tcp:name.cloudapp.net,1433
In terms of what you are doing with jQuery, my understanding is that you can chain functions like you have and the inner ones have access to variables from the outer ones. So is your ShowDialog(x) function contains these other functions, you can re-use the x variable within them and it will be taken as a reference to the parameter from the outer function.
I agree with mausch, you should really look at using POST for these actions, which will add a <form>
tag around each element, but make the chances of an automated script or tool triggering the Cancel event much less likely. The Change action can remain as is because it (presumably just opens an edit form).
Well, here is one solution I ended up with, but I hope there's a more elegant one...
StringBuilder result = new StringBuilder();
for(int i=0; i<name.length(); i++) {
char tmpChar = name.charAt( i );
if (Character.isLetterOrDigit( tmpChar) || tmpChar == '_' ) {
result.append( tmpChar );
}
}
result
ends up with the desired result...
import datetime, time
def convert_enddate_to_seconds(self, ts):
"""Takes ISO 8601 format(string) and converts into epoch time."""
dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
datetime.timedelta(hours=int(ts[-5:-3]),
minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
return seconds
This also includes the milliseconds and time zone.
If the time is '2012-09-30T15:31:50.262-08:00', this will convert into epoch time.
>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26
Use android vollley, it is very fast and you can betterm manipulate requests. Send post request using Volley and receive in PHP
Basically, you will create a map with key-value params for the php request(POST/GET), the php will do the desired processing and you will return the data as JSON(json_encode()). Then you can either parse the JSON as needed or use GSON from Google to let it do the parsing.
There's one more (at least) road to Rome:
static const char HELLO3[] = "Howdy";
(static
— optional — is to prevent it from conflicting with other files). I'd prefer this one over const char*
, because then you'll be able to use sizeof(HELLO3)
and therefore you don't have to postpone till runtime what you can do at compile time.
The define has an advantage of compile-time concatenation, though (think HELLO ", World!"
) and you can sizeof(HELLO)
as well.
But then you can also prefer const char*
and use it across multiple files, which would save you a morsel of memory.
In short — it depends.
In Swift Language, if you want to show you need to use it in this way. To assign double value in UITextView, for example:
let result = 23.954893
resultTextView.text = NSString(format:"%.2f", result)
If you want to show in LOG like as objective-c does using NSLog(), then in Swift Language you can do this way:
println(NSString(format:"%.2f", result))
I was able to install libc6 2.17
in Debian Wheezy
by editing the recommendations in perror's answer:
IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1.
Then you can stop x (slim
) with sudo /etc/init.d/slim stop
(replace slim with mdm
or lightdm
or whatever)
Add the following line to the file /etc/apt/sources.list
:
deb http://ftp.debian.org/debian experimental main
Should be changed to:
deb http://ftp.debian.org/debian sid main
Then follow the rest of perror's post:
Update your package database:
apt-get update
Install the eglibc
package:
apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg
IMPORTANT
After done updating libc6
, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main
), or else you risk upgrading your whole distro to sid.
Hope this helps. It took me a while to figure out.
Android doesn't support keeping the spaces at the end of the string in String.xml file so if you want space after string you need to use this unicode in between the words.
\u0020
It is a unicode space character.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class M{
public static void main(String[] args) {
HashMap<String, List<String>> resultHashMap = new HashMap<String, List<String>>();
Set<String> newKeyList = resultHashMap.keySet();
for (Iterator<String> iterator = originalHashMap.keySet().iterator(); iterator.hasNext();) {
String hashKey = (String) iterator.next();
if (!newKeyList.contains(originalHashMap.get(hashKey))) {
List<String> loArrayList = new ArrayList<String>();
loArrayList.add(hashKey);
resultHashMap.put(originalHashMap.get(hashKey), loArrayList);
} else {
List<String> loArrayList = resultHashMap.get(originalHashMap
.get(hashKey));
loArrayList.add(hashKey);
resultHashMap.put(originalHashMap.get(hashKey), loArrayList);
}
}
System.out.println("Original HashMap : " + originalHashMap);
System.out.println("Result HashMap : " + resultHashMap);
}
}
also if you are running SharePoint and encounter this error, don't forget to run
Enable-SPSessionStateService -DefaultProvision
or you will continue to receive the above error message.
this works fine for me..
$host="127.0.0.1";
$output=shell_exec('ping -n 1 '.$host);
echo "<pre>$output</pre>"; //for viewing the ping result, if not need it just remove it
if (strpos($output, 'out') !== false) {
echo "Dead";
}
elseif(strpos($output, 'expired') !== false)
{
echo "Network Error";
}
elseif(strpos($output, 'data') !== false)
{
echo "Alive";
}
else
{
echo "Unknown Error";
}
Found a really helpful link for that. Using SQLCMD for this is really easier than solving this with a stored procedure
http://www.excel-sql-server.com/sql-server-export-to-excel-using-bcp-sqlcmd-csv.htm
I really like the description and the example from http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Visitor.html.
The assumption is that you have a primary class hierarchy that is fixed; perhaps it’s from another vendor and you can’t make changes to that hierarchy. However, your intent is that you’d like to add new polymorphic methods to that hierarchy, which means that normally you’d have to add something to the base class interface. So the dilemma is that you need to add methods to the base class, but you can’t touch the base class. How do you get around this?
The design pattern that solves this kind of problem is called a “visitor” (the final one in the Design Patterns book), and it builds on the double dispatching scheme shown in the last section.
The visitor pattern allows you to extend the interface of the primary type by creating a separate class hierarchy of type Visitor to virtualize the operations performed upon the primary type. The objects of the primary type simply “accept” the visitor, then call the visitor’s dynamically-bound member function.
There are two ways of looking at github content, the "raw" way and the "Web page" way.
raw.githubusercontent.com
returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.
If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com
.
To see the content of raw.githubusercontent.com/${repo}/${branch}/${path}
in the usual github interface:
raw.githubusercontent.com
with plain github.com
In this case, the branch name is "master" (which is a very common branch name), so you replace /master/
with /blob/master/
, and so
https://raw.githubusercontent.com/Homebrew/install/master/install
becomes
https://github.com/Homebrew/install/blob/master/install
This is the reverse of finding a file on Github and clicking the Raw link.
IrishChieftain didn't really address the question, so here's my take:
eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.
I managed to install php54w according to Simon's suggestion, but then my sites stopped working perhaps because of an incompatibility with php-mysql or some other module. Even frantically restoring the old situation was not amusing: for anyone in my own situation the sequence is:
sudo yum remove php54w
sudo yum remove php54w-common
sudo yum install php-common
sudo yum install php-mysql
sudo yum install php
It would be nice if someone submitted the full procedure to update all the php packet. That was my production server and my heart is still rapidly beating.
Another similar case: most compilers won't optimize a + b + c + d
to (a + b) + (c + d)
(this is an optimization since the second expression can be pipelined better) and evaluate it as given (i.e. as (((a + b) + c) + d)
). This too is because of corner cases:
float a = 1e35, b = 1e-5, c = -1e35, d = 1e-5;
printf("%e %e\n", a + b + c + d, (a + b) + (c + d));
This outputs 1.000000e-05 0.000000e+00
As I continue to recieve upvotes on this, I think it is reasonable to remember that this answer is 4 years old. Web has grown in a really fast pace, so please be mindful about this answer.
I had the same issue recently and researched about the subject.
The solution given is called long polling, and to correctly use it you must be sure that your AJAX request has a "large" timeout and to always make this request after the current ends (timeout, error or success).
Here, to keep code short, I will use jQuery:
function pollTask() {
$.ajax({
url: '/api/Polling',
async: true, // by default, it's async, but...
dataType: 'json', // or the dataType you are working with
timeout: 10000, // IMPORTANT! this is a 10 seconds timeout
cache: false
}).done(function (eventList) {
// Handle your data here
var data;
for (var eventName in eventList) {
data = eventList[eventName];
dispatcher.handle(eventName, data); // handle the `eventName` with `data`
}
}).always(pollTask);
}
It is important to remember that (from jQuery docs):
In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.
It is not in any specific language, but it would be something like this:
function handleRequest () {
while (!anythingHappened() || hasTimedOut()) { sleep(2); }
return events();
}
Here, hasTimedOut
will make sure your code does not wait forever, and anythingHappened
, will check if any event happend. The sleep
is for releasing your thread to do other stuff while nothing happens. The events
will return a dictionary of events (or any other data structure you may prefer) in JSON format (or any other you prefer).
It surely solves the problem, but, if you are concerned about scalability and perfomance as I was when researching, you might consider another solution I found.
Use sockets!
On client side, to avoid any compatibility issues, use socket.io. It tries to use socket directly, and have fallbacks to other solutions when sockets are not available.
On server side, create a server using NodeJS (example here). The client will subscribe to this channel (observer) created with the server. Whenever a notification has to be sent, it is published in this channel and the subscriptor (client) gets notified.
If you don't like this solution, try APE (Ajax Push Engine).
Hope I helped.
I have also dealt with this exception after a fully working context.xml setup was adjusted. I didn't want environment details in the context.xml, so I took them out and saw this error. I realized I must fully create this datasource resource in code based on System Property JVM -D args.
Original error with just user/pwd/host removed: org.apache.tomcat.jdbc.pool.ConnectionPool init SEVERE: Unable to create initial connections of pool.
Removed entire contents of context.xml and try this: Initialize on startup of app server the datasource object sometime before using first connection. If using Spring this is good to do in an @Configuration bean in @Bean Datasource constructor.
package to use: org.apache.tomcat.jdbc.pool.*
PoolProperties p = new PoolProperties();
p.setUrl(jdbcUrl);
p.setDriverClassName(driverClass);
p.setUsername(user);
p.setPassword(pwd);
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setValidationQueryTimeout(100);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(5);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(60);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(5);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors(
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
"org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
ds.setPoolProperties(p);
return ds;
No. Its not possible to add link through css. But you can use jquery
$('.case').each(function() {
var link = $(this).html();
$(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});
Here the demo: http://jsfiddle.net/r5uWX/1/
AngularJS Developer Guide - CSS classes used by AngularJS
- @property {boolean} $untouched True if control has not lost focus yet.
- @property {boolean} $touched True if control has lost focus.
- @property {boolean} $pristine True if user has not interacted with the control yet.
- @property {boolean} $dirty True if user has already interacted with the control.
Use build job plugin for that task in order to trigger other jobs from jenkins file. You can add variety of logic to your execution such as parallel ,node and agents options and steps for triggering external jobs. I gave some easy-to-read cookbook example for that.
1.example for triggering external job from jenkins file with conditional example:
if (env.BRANCH_NAME == 'master') {
build job:'exactJobName' , parameters:[
string(name: 'keyNameOfParam1',value: 'valueOfParam1')
booleanParam(name: 'keyNameOfParam2',value:'valueOfParam2')
]
}
2.example triggering multiple jobs from jenkins file with conditionals example:
def jobs =[
'job1Title'{
if (env.BRANCH_NAME == 'master') {
build job:'exactJobName' , parameters:[
string(name: 'keyNameOfParam1',value: 'valueNameOfParam1')
booleanParam(name: 'keyNameOfParam2',value:'valueNameOfParam2')
]
}
},
'job2Title'{
if (env.GIT_COMMIT == 'someCommitHashToPerformAdditionalTest') {
build job:'exactJobName' , parameters:[
string(name: 'keyNameOfParam3',value: 'valueOfParam3')
booleanParam(name: 'keyNameOfParam4',value:'valueNameOfParam4')
booleanParam(name: 'keyNameOfParam5',value:'valueNameOfParam5')
]
}
}
Since the UI of the facebook has changed recently, here's the latest update for setting the sandbox mode ON/OFF :
Click on the Apps menu on the top bar.
Select the respective app from the drop down.
Go to 'Status & Review' from the table in the left side of the page.
Do you want to make this app and all its live features available to the general public? - Select switch to set YES/NO value.
Update: The YES/NO button will be disabled until and unless you provide your contact email.
Go to "Settings" in the left menu.
Update your Contact Email.
Hit the "Save" button at the bottom of the page.
Update: 'Status & Review' is replaced by 'App Review' now
String literals and constants are interned by default.
That is, "foo" == "foo"
(declared by the String literals), but new String("foo") != new String("foo")
.
<div id="map" style="width:100%;height:500px"></div>
<script>
function myMap() {
var myCenter = new google.maps.LatLng(51.508742,-0.120850);
var mapCanvas = document.getElementById("map");
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({position:myCenter});
marker.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
You're close, but you want name to be an XAttribute
rather than XElement
:
XDocument doc = XDocument.Load(spath);
XElement root = new XElement("Snippet");
root.Add(new XAttribute("name", "name goes here"));
root.Add(new XElement("SnippetCode", "SnippetCode"));
doc.Element("Snippets").Add(root);
doc.Save(spath);
The easiest workaround I have found is to use Firefox. Not only does it work with no extra steps (drag and drop - no muss no fuss), but blackboxing works better than Chrome.
Or even just
git version
Results in something like
git version 1.8.3.msysgit.0
For Mac users who only have Command Line Tools instead of Xcode, check the /Library/Developer/CommandLineTools
directory, for example::
"configurations": [{
"name": "Mac",
"includePath": [
"/usr/local/include",
// others, e.g.: "/usr/local/opt/ncurses/include",
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include",
"${workspaceFolder}/**"
]
}]
You probably need to adjust the path if you have different version of Command Line Tools installed.
Note: You can also open/generate the
c_cpp_properties.json
file via theC/Cpp: Edit Configurations
command from the Command Palette (??P).
I understand using a global variable is sometimes the most convenient thing to do, especially in cases where usage of class makes the easiest thing so much harder (e.g., multiprocessing
). I ran into the same problem with declaring global variables and figured it out with some experiments.
The reason that g_c
was not changed by the run
function within your class is that the referencing to the global name within g_c
was not established precisely within the function. The way Python handles global declaration is in fact quite tricky. The command global g_c
has two effects:
Preconditions the entrance of the key "g_c"
into the dictionary accessible by the built-in function, globals()
. However, the key will not appear in the dictionary until after a value is assigned to it.
(Potentially) alters the way Python looks for the variable g_c
within the current method.
The full understanding of (2) is particularly complex. First of all, it only potentially alters, because if no assignment to the name g_c
occurs within the method, then Python defaults to searching for it among the globals()
. This is actually a fairly common thing, as is the case of referencing within a method modules that are imported all the way at the beginning of the code.
However, if an assignment command occurs anywhere within the method, Python defaults to finding the name g_c
within local variables. This is true even when a referencing occurs before an actual assignment, which will lead to the classic error:
UnboundLocalError: local variable 'g_c' referenced before assignment
Now, if the declaration global g_c
occurs anywhere within the method, even after any referencing or assignment, then Python defaults to finding the name g_c
within global variables. However, if you are feeling experimentative and place the declaration after a reference, you will be rewarded with a warning:
SyntaxWarning: name 'g_c' is used prior to global declaration
If you think about it, the way the global declaration works in Python is clearly woven into and consistent with how Python normally works. It's just when you actually want a global variable to work, the norm becomes annoying.
Here is a code that summarizes what I just said (with a few more observations):
g_c = 0
print ("Initial value of g_c: " + str(g_c))
print("Variable defined outside of method automatically global? "
+ str("g_c" in globals()))
class TestClass():
def direct_print(self):
print("Directly printing g_c without declaration or modification: "
+ str(g_c))
#Without any local reference to the name
#Python defaults to search for the variable in globals()
#This of course happens for all the module names you import
def mod_without_dec(self):
g_c = 1
#A local assignment without declaring reference to global variable
#makes Python default to access local name
print ("After mod_without_dec, local g_c=" + str(g_c))
print ("After mod_without_dec, global g_c=" + str(globals()["g_c"]))
def mod_with_late_dec(self):
g_c = 2
#Even with a late declaration, the global variable is accessed
#However, a syntax warning will be issued
global g_c
print ("After mod_with_late_dec, local g_c=" + str(g_c))
print ("After mod_with_late_dec, global g_c=" + str(globals()["g_c"]))
def mod_without_dec_error(self):
try:
print("This is g_c" + str(g_c))
except:
print("Error occured while accessing g_c")
#If you try to access g_c without declaring it global
#but within the method you also alter it at some point
#then Python will not search for the name in globals()
#!!!!!Even if the assignment command occurs later!!!!!
g_c = 3
def sound_practice(self):
global g_c
#With correct declaration within the method
#The local name g_c becomes an alias for globals()["g_c"]
g_c = 4
print("In sound_practice, the name g_c points to: " + str(g_c))
t = TestClass()
t.direct_print()
t.mod_without_dec()
t.mod_with_late_dec()
t.mod_without_dec_error()
t.sound_practice()
Two simple solutions. Works also for infinities and numbers -1 <= r <= 1 Will return "positive" for NaNs.
String positiveOrNegative(double number){
return (((int)(number/0.0))>>31 == 0)? "positive" : "negative";
}
String positiveOrNegative(double number){
return (number==0 || ((int)(number-1.0))>>31==0)? "positive" : "negative";
}
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
Step 1: Restart VS Code as an adminstrator
(click the windows key, search for "Visual Studio Code", right click, and you'll see the administrator option)
Step 2: In your VS code powershell terminal run Set-ExecutionPolicy Unrestricted
I'm not really sure of your question, but if all you really want is list currently opened screen session, try:
screen -ls
(Update: August 2011)
As geofflane mentions in his answer, Java 7 now support named groups.
tchrist points out in the comment that the support is limited.
He details the limitations in his great answer "Java Regex Helper"
Java 7 regex named group support was presented back in September 2010 in Oracle's blog.
In the official release of Java 7, the constructs to support the named capturing group are:
(?<name>capturing text)
to define a named group "name"\k<name>
to backreference a named group "name"${name}
to reference to captured group in Matcher's replacement stringMatcher.group(String name)
to return the captured input subsequence by the given "named group".
Other alternatives for pre-Java 7 were:
(Original answer: Jan 2009, with the next two links now broken)
You can not refer to named group, unless you code your own version of Regex...
That is precisely what Gorbush2 did in this thread.
(limited implementation, as pointed out again by tchrist, as it looks only for ASCII identifiers. tchrist details the limitation as:
only being able to have one named group per same name (which you don’t always have control over!) and not being able to use them for in-regex recursion.
Note: You can find true regex recursion examples in Perl and PCRE regexes, as mentioned in Regexp Power, PCRE specs and Matching Strings with Balanced Parentheses slide)
Example:
String:
"TEST 123"
RegExp:
"(?<login>\\w+) (?<id>\\d+)"
Access
matcher.group(1) ==> TEST
matcher.group("login") ==> TEST
matcher.name(1) ==> login
Replace
matcher.replaceAll("aaaaa_$1_sssss_$2____") ==> aaaaa_TEST_sssss_123____
matcher.replaceAll("aaaaa_${login}_sssss_${id}____") ==> aaaaa_TEST_sssss_123____
(extract from the implementation)
public final class Pattern
implements java.io.Serializable
{
[...]
/**
* Parses a group and returns the head node of a set of nodes that process
* the group. Sometimes a double return system is used where the tail is
* returned in root.
*/
private Node group0() {
boolean capturingGroup = false;
Node head = null;
Node tail = null;
int save = flags;
root = null;
int ch = next();
if (ch == '?') {
ch = skip();
switch (ch) {
case '<': // (?<xxx) look behind or group name
ch = read();
int start = cursor;
[...]
// test forGroupName
int startChar = ch;
while(ASCII.isWord(ch) && ch != '>') ch=read();
if(ch == '>'){
// valid group name
int len = cursor-start;
int[] newtemp = new int[2*(len) + 2];
//System.arraycopy(temp, start, newtemp, 0, len);
StringBuilder name = new StringBuilder();
for(int i = start; i< cursor; i++){
name.append((char)temp[i-1]);
}
// create Named group
head = createGroup(false);
((GroupTail)root).name = name.toString();
capturingGroup = true;
tail = root;
head.next = expr(tail);
break;
}