_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d16101 | val | It's not going to be the answer your boss wants to hear, but last time I looked into this there's no reliable way of knowing when someone has opened an email you've sent.
Traditionally (to find out email read counts for marketing emails) it's been done by embedding an image in the email and then having the loading of that image from your server trigger some action; you could do this and have the image address point to a script which sends the auto response then returns a single pixel transparent gif (for example), but it's becoming more standard to disable images in emails these days, so that isn't a 100% reliable route.
That said, if the people you send emails to are more likely than not to load non-embedded images, that is one way to achieve it :)
A: Read Receipts are not available in GMail:
http://www.google.com/support/forum/p/gmail/thread?tid=3ad9e2c7914d3f0e&hl=en
There's not much support for this feature in many email clients. It's a privacy issue. | unknown | |
d16102 | val | Const objects cannot be assigned to. You must set the value of the const member upon initialisation. If you initialise to null, then it will always be null. So, don't initialise to null. In order to let the derived class choose what to initialise it to, use a constructor argument:
Base::Base(BaseDataClass *);
You can use that argument to initialise the member.
That said:
*
*If you use new in constructor, you should make sure that you eventually delete it or else you will leak memory.
*You cannot delete through the pointer to base, because the destructor of the base is not virtual.
*Bare owning pointers are a bad design. You should use smart pointers instead. | unknown | |
d16103 | val | Assuming you have grades in B2:B100 and dates in 5 columns C2:G100 then you can use this formula to count the number of students with a specific grade who took courses in a specific date period.
=SUMPRODUCT((MMULT((C$2:G$100>=J2)*(C$2:G$100<=K2)*(B$2:B$100=I2),{1;1;1;1;1})>0)+0)
where J2 and K2 are the start and end dates of the period (1-Jan-2012 and 1-Mar-2012) and I2 is a specific grade (C)
the {1;1;1;1;1} part depends on the number of date columns, so if there are 7 date columns then you need to change that to {1;1;1;1;1;1;1}.....or you make the formula dynamically adjust by using this version
=SUM((MMULT((C$2:G$100>=J2)*(C$2:G$100<=K2)*(B$2:B$100=I2),TRANSPOSE(COLUMN(C2:G100))^0)>0)+0)
The latter formula, though, is an "array formula" which you need to confirm with CTRL+SHIFT+ENTER
Update
For the number of distinct grades within a specific date range then assuming you have a finite list of possible grades then list those somewhere on the worksheet, e.g. M2:M10 and then you can use this "array formula"
=SUM(1-ISNA(MATCH(M$2:M$10,IF(MMULT((C$2:G$100>=J2)*(C$2:G$100<=K2),{1;1;1;1;1}),B$2:B$100),0)))
confirmed with CTRL+SHIFT+ENTER | unknown | |
d16104 | val | That column is populated for media types that are used directly in actions - that is, explicitly selected in the dropdown in action properties.
By default actions do not limit to any media types and all media types will be used as per the user media entries and various filters. | unknown | |
d16105 | val | If you donβt need the groupings (the βHire as chefβ and βSeek dinner invitationβ headings), then DataGrid should get you close. You can bind its ItemsSource to your collection of items, and define custom columns bound to your itemsβ properties.
For example, you can use a DataGridTextColumn for βOccupationβ, DataGridCheckBoxColumn for βTells Jokes?β, and DataGridTemplateColumn for more complex properties which require a custom DataTemplate to visualize, such as the main βPersonβ column or βCooking skillβ.
Edi: It appears that the DataGrid does support grouping as well.
A: You should go for ListView
http://msdn.microsoft.com/en-us/library/ms754027(v=vs.90).aspx | unknown | |
d16106 | val | One way to do it is to give options when you create the Instance. E.g.:
i = vlc.Instance((' --sub-file <your srt file> '))
I have gotten this to work. | unknown | |
d16107 | val | *
*Dont extend JFrame call unnecessarily
*Dont use null/Absolute LayoutManager
*why use show() to set JFrame visible? you should be using setVisible(true)
*Dont forget Swing components should be created a manipulated on Event Dispatch Thread via SwingUtilities.invokeXXX and JavaFX components via Platform.runLater()
Besides the above the biggest problem you have is that you dont refresh GUI/container after adding/removing components,thus no changes are shown.:
call revalidate() and repaint() on JFrame instance to reflect changes after adding/removing components from a visible container. | unknown | |
d16108 | val | SQL DEMO
Convert the text to DATE
SELECT to_date(application_date,'DDMONYYYY');
then
SELECT MAX(to_date(application_date,'DDMONYYYY')),
MIN(to_date(application_date,'DDMONYYYY'))
;
A: Try this:
select max(TO_DATE(application_date, 'DDMONYYYY')) max_date,
min(TO_DATE(application_date, 'DDMONYYYY')) min_date
from table1 | unknown | |
d16109 | val | I found a way to overcome my problem. I removed the scriptArguments XML, the CmdletBinding and the param declaration completely. Instead I simply access the variables at the beginning of the jetbrains_powershell_script_code XML:
$Optional = "%Optional%"
$Required = "%Required%"
The required check is done by TeamCity's validationMode property further up the XML. | unknown | |
d16110 | val | Since you don't specify any requirements, I suggest starting with the most naive mapping at first:
root
schools
1: "name of school1"
2: "name of school2"
users:
1: { "name": "Maeh", "email": "[email protected]" }
2: { "name": "Frank", "email": "[email protected]" }
schools_users:
1_1: "20141031"
1_2: "20130102" | unknown | |
d16111 | val | See Java "constant string too long" compile error. Only happens using Ant, not when using Eclipse
there ist stated that the length of a string constant in a class file is limited to 2^16 bytes in UTF-8 encoding.
If you don't use such a long constant, maybe the otpimizing compiler makes some concatenation with static expressions in the main function.
A: You should be able to get a String of length Integer.MAX_VALUE (always 2147483647 (231 - 1) by the Java specification, the maximum size of an array, which the String class uses for internal storage) or half your maximum heap size (since each character is two bytes), whichever is smaller. | unknown | |
d16112 | val | I shared you my example makefile(I can't type all of them in comment section, if not answer your question, pls let me know):
Here is my folder view:
./
βββ debug
βΒ Β βββ debug.c
βΒ Β βββ debug.h
βΒ Β βββ uart_print.c
βββ driver
βΒ Β βββ driver.c
βΒ Β βββ driver.h
βββ include
βΒ Β βββ common.h
βββ Makefile
βββ root
βΒ Β βββ main.c
βββ tc
βΒ Β βββ boot.c
βΒ Β βββ boot.h
βΒ Β βββ connect.c
βΒ Β βββ connect.h
βΒ Β βββ ffs.c
βΒ Β βββ ffs.h
βΒ Β βββ gpio.c
βΒ Β βββ gpio.h
βΒ Β βββ i2c.c
βΒ Β βββ i2c.h
βΒ Β βββ network.c
βΒ Β βββ network.h
βΒ Β βββ power.c
βΒ Β βββ power.h
βΒ Β βββ product.c
βΒ Β βββ product.h
βΒ Β βββ spi.c
βΒ Β βββ spi.h
βββ utility
Β Β βββ utility.c
Β Β βββ utility.h
Makefile1, did not generate lib
CC := gcc
LD := gcc
COLOR_ON := color
COLOR_OFF :=
PROGRAM = gSmokeTest
MAKE_DIR = $(PWD)
MODULES := debug driver utility tc root
SRC_DIR := $(addprefix $(MAKE_DIR)/,$(MODULES))
BUILD_DIR := $(MAKE_DIR)/output
SRC := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.c))
OBJ := $(patsubst %.c,%.o,$(SRC))
INCLUDES := $(addprefix -I,$(SRC_DIR))
INCLUDES += -I$(MAKE_DIR)/include
CFLAGS :=
CFLAGS += -Wall -O -ggdb -Wstrict-prototypes -Wno-pointer-sign #-Werror# -finstrument-functions -fdump-rtl-expand
#CFLAGS += -D_DEBUG_ -D_REENTRANT
TC_DEF :=
#TC_DEF += -D_POWER_SOS_
#TC_DEF += -D_PRODUCT_
#TC_DEF += -D_CONNECT_
TC_DEF += -D_SPI_
#TC_DEF += -D_I2C_
#TC_DEF += -D_POWER_
#TC_DEF += -D_BOOT_
#TC_DEF += -D_NETWORK_
vpath %.c $(SRC_DIR)
define make-goal
$1/%.o: %.c
@$(COLOR_ON)$(CC) $(TC_DEF) $(CFLAGS) $(INCLUDES) -c $$< -o $$@
@echo "Compile $$*.c"
endef
.PHONY: all checkdirs clean help flowchart
all: checkdirs $(BUILD_DIR)/$(PROGRAM)
$(BUILD_DIR)/$(PROGRAM): $(OBJ)
@$(LD) $^ -o $@
@echo "Generate $(PROGRAM)"
checkdirs: $(BUILD_DIR)
$(BUILD_DIR):
mkdir -p $@
clean:
rm -f $(OBJ) $(BUILD_DIR)/$(PROGRAM)
rm -rf $(BUILD_DIR)
help:
@echo "SRC DIR: $(SRC_DIR)"
@echo "Build DIR: $(BUILD_DIR)"
@echo "Source: $(SRC)"
@echo "Obj: $(OBJ)"
@echo "Includes: $(INCLUDES)"
flowchart:
@cflow2dot pdf ${SRC}
$(foreach sdir,$(SRC_DIR),$(eval $(call make-goal,$(sdir))))
Then, I setup another folder structure(make it simple, delete some files) and this time I generated lib:
./
βββ debug
βΒ Β βββ debug.h
βΒ Β βββdebug.mk
βββ driver
βΒ Β βββ driver.h
βΒ Β βββ driver.mk
βΒ Β βββ driver.o
βββ include
βΒ Β βββ common.h
βββ libs
βΒ Β βββ libdebug.a
βΒ Β βββ libdrv.a
βΒ Β βββ libtc.a
βΒ Β βββ libutility.a
βββ make
βΒ Β βββ connect.d
βΒ Β βββ debug.d
βΒ Β βββ driver.d
βΒ Β βββ makefile
βΒ Β βββ network.d
βΒ Β βββ uart_print.d
βΒ Β βββ utility.d
βββ Makefile
βββ prog
βΒ Β βββ DEMO.map
βββ root
βΒ Β βββ main.c
βΒ Β βββ root.mk
βββ rules.mk
βββ tc
βΒ Β βββ connect.h
βΒ Β βββ network.h
βΒ Β βββ tc.mk
βββ tools.mk
βββ utility
βββ utility.h
βββutility.mk
Makefile2.1, top makefile:
CC := gcc
LD := gcc
MAKE_DIR = $(PWD)
MODULES := root tc utility driver debug
SRC_DIR := $(addprefix ${MAKE_DIR}/,$(MODULES))
#BUILD_DIR := $(addprefix ${MAKE_DIR}/,$(MODULES))
SRC := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.c))
#OBJ := $(patsubst ${SRC_DIR}/%.c,${BUILD_DIR}/%.o,$(SRC))
#OBJ := $(foreach sdir,$(SRC_DIR),$(patsubst $(sdir)/%.c,$(BUILD_DIR)/%.o,$(filter $(sdir)/%,$(SRC))))
OBJ := $(patsubst %.c,%.o,$(SRC))
INCLUDES := $(addprefix -I,$(SRC_DIR))
vpath %.c $(SRC_DIR)
#SRC_F = $(foreach sdir,$(SRC_DIR),$(filter $(SRC_DIR)/%,$(SRC)))
#OBJ_F = $(patsubst $(SRC_F)/%.c, $(BUILD_DIR)/%.o, $(SRC_F))
default:
@echo "SRC DIR: ${SRC_DIR}"
# @echo "Build DIR: ${BUILD_DIR}"
@echo "Source: ${SRC}"
@echo "Obj: ${OBJ}"
@echo "Includes: ${INCLUDES}"
# @echo "SRC_F: ${SRC_F}"
# @echo "OBJ_F: ${OBJ_F}"
define make-goal
$1/%.o: %.c
$(CC) $(INCLUDES) -c $$< -o $$@
endef
all: test
test: $(OBJ)
$(LD) $^ -o $@
#$(foreach sdir,$(SRC_DIR),$(eval $(call make-goal,$(sdir))))
#.PHONY: all checkdirs clean
#
#all: checkdirs build/test
#
#build/test: $(OBJ)
# $(LD) $^ -o $@
#
#
#checkdirs: $(BUILD_DIR)
#
#$(BUILD_DIR):
# @mkdir -p $@
#
clean:
rm -f $(OBJ) test
#
$(foreach sdir,$(SRC_DIR),$(eval $(call make-goal,$(sdir))))
#
and in each module, I have individual mk file, generated self lib:
#you just need change this MODULE name
MODULE = debug
LIB = $(LIB_DIR)/lib$(MODULE).a
SRCS = $(wildcard *.c)
OBJS = $(patsubst %.c, %.o, $(SRCS))
DEPS = $(patsubst %.c, %.d, $(SRCS))
$(LIB): $(OBJS)
@mkdir -p ../libs
@$(AR) cr $@ $^
@echo " Archive $(notdir $@)"
#$(OBJS): $(SRCS)
%.o: %.c
@$(CC) $(CFLAGS) -o $@ -c $<
@echo " CC $@"
# Automatic dependency magic:
#%.d: %.c
# $(CC) -MM $(CFLAGS) $@ > $<
#-include (SRCS:%.c=%.d)
.PHONY: clean
clean:
@$(RM) -f $(LIB) $(OBJS) $(DEPS)
@$(RM) -f *.expand
@echo " Remove Objects: $(OBJS)"
@echo " Remove Libraries: $(notdir $(LIB))"
@echo " Remove Dependency: $(DEPS)"
.PHONY: lint
lint:
$(LINT) $(INC_SRCH_PATH) $(SRCS) | unknown | |
d16113 | val | You can use CSS-Variables for this.
Define your colors to ':root' in your css file:
:root{
--myColor: red;
--mySecondColor:green;
}
then set the colorProperties in your elements like this:
button{
background-color: var(--myColor);
padding:10px;
}
div{
color: var(--mySecondColor);
padding:10px;
}
Now in JavaScript you can change these properties globally
document.documentElement.style.setProperty('--myColor','blue');
document.documentElement.style.setProperty('--mySecondColor','orange');
Or change it just local
document.querySelector('button').style.setProperty('--myColor','blue'); | unknown | |
d16114 | val | What you want is a called a "category". With categories you can extend NSString (and add your method).
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html | unknown | |
d16115 | val | So the true opensource way: there is no such a feature? Clone a repo, implement a feature, create pull request, ?????, PROFIT!!!!1
https://github.com/sebastianbergmann/phpunit-selenium/pull/212
Now phpunit_selenium2 supports double click. You can use it like:
$this->moveto($element);
$this->doubleclick();
Correspondent example from the tests | unknown | |
d16116 | val | this piece of code may help you and it is self explanatory...
public class TestActivity extends Activity {
private int rotation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
rotation = savedInstanceState.getInt("ANGLE");
}
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
final Button button = (Button) findViewById(R.id.iv_icon);
DisplayMetrics metrics = getResources().getDisplayMetrics();
final int width = metrics.widthPixels;
final int height = metrics.heightPixels;
final Bitmap imageBitmap = BitmapFactory.decodeResource(
getResources(), R.drawable.image1);
final Bitmap scaledBitmap = Bitmap.createScaledBitmap(imageBitmap, width, height, true);
imageView.setImageBitmap(getRotatedBitmap(scaledBitmap));
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
rotation += 90;
rotation %= 360;
Bitmap bitmap = getRotatedBitmap(scaledBitmap);
imageView.setImageBitmap(bitmap);
}
});
}
private Bitmap getRotatedBitmap(Bitmap bitmap) {
if (rotation % 360 == 0) {
return bitmap;
}
Matrix matrix = new Matrix();
matrix.postRotate(rotation, bitmap.getWidth() / 2,
bitmap.getHeight() / 2);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight() / 2, matrix, true);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("ANGLE", rotation);
super.onSaveInstanceState(outState);
}
}
A: yourimage.setRotation(yourimage.getRotation() + 90);
A: In manifest file, lock your screen orientation like this:
android:screenOrientation="portrait"
or
android:screenOrientation="landscape" | unknown | |
d16117 | val | If you want something to print all the rows you have to keep you what you have already printed so you have to do something like this :
for(var j = 0; j < 10; j++) {
document.getElementById("myResults").innerHTML =
document.getElementById("myResults").innerHTML + locations[j] + "<br>";
}
You can see it there:
http://jsfiddle.net/Ba8TU/ | unknown | |
d16118 | val | The easiest way would be to just read the whole file:
fh = open("./test.txt")
lines = fh.readlines()
for i in range(len(lines) - 2):
print(lines[i])
print(lines[i + 2])
A: and Welcome to Stackoverflow
You can try this.
left = next(fh)
center = next(fh)
while True:
try:
right = next(fh)
except StopIteration:
break
print('{}\n{}'.format(left, right)
left = center
center = right
This returns
line0
line2
line1
line3
line2
line4
line3
line5
and so on...
A: You can use itertools.tee to replicate the file iterator, skip the first two values of the second iterator returned by tee, and then zip the two iterators to produce the desired pairs of lines so that you can chain and join them for output:
from itertools import tee, chain
l, n = tee(fh)
next(n)
next(n)
print(''.join(chain.from_iterable(zip(l, n))))
With your sample input, this outputs:
line0
line2
line1
line3
line2
line4
line3
line5
line4
line6
line5
line7
line6
line8
line7
line9
A: also an option which does not read the whole file in one go but just stores 2 lines at a time:
txt = """line0
line1
line2
line3
line4
line5
line6
line7
line8
line9"""
with StringIO(txt) as file:
a, b = next(file), next(file)
for c in file:
print(a, end='')
print(c, end='')
a, b = b, c
with the output
line0
line2
line1
line3
line2
line4
line3
line5
line4
line6
line5
line7
line6
line8
line7
line9
you'd have to replace the StringIO part with your file of course.
A: Here is a generator that handles any number of lines including odd length files:
def alternate(f):
write = False
for line in f:
if not write:
keep = line
else:
yield line
yield keep
write = not write
if write: # handle odd-line-count files.
yield line
with open('test.txt') as f:
for line in alternate(f):
print(line,end='')
Example input (odd length):
line0
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
Output:
line1
line0
line3
line2
line5
line4
line7
line6
line9
line8
line10 | unknown | |
d16119 | val | A 'parity bit' is a method of error checking. Imagine that you need to send 8 bits over a connection and determine whether they got through right. You could try sending it twice, that way if there is an error, the receiver will know because the two messages differ. However, this requires two times the bandwidth, which is too much. So often every byte (8 bits) will also have a parity bit. You count up the number of ones in the byte. If it is odd, the parity bit is one. If it is even, the parity bit is zero. That way if there is any single error the receiver will know and only one eighth the extra bandwidth is needed. Examples:
Data: 01001001 3 ones, parity bit 1
Data: 00110101 4 ones, parity bit 0
If receiver gets 00111101 and parity bit 0, it will know that there is some corruption.
Of course if there are two errors in the same byte there will be no way to detect this - example if original is 00000001 and received is 00000010 - but this is considered to be rare enough to not worry for most applications.
A: The first sentence of the Wikipedia article is clear enough, and so is the second paragraph... But ohwell.
Given a word of n bits, with n-1 bits to check parity on and 1 bit of parity, the parity bit will be set to:
*
*1 if the number of bits set to 1 is odd, 0 otherwise (even parity);
*0 if the number of bits set to 1 is even, 1 otherwise (odd parity).
Example: 1101011x where x is the parity bit. There are 5 bits set to 1, therefore an odd number: x will be set to 1 (even parity) or 0 (odd parity). | unknown | |
d16120 | val | Use perror() to print the human-readable error string when connect() or most other unix-like system calls return an error. But since you told us the value of errno, I looked in errno.h for the meaning, and found:
#define ETIMEDOUT 110 /* Connection timed out */
#define ECONNREFUSED 111 /* Connection refused */
(BTW, you cannot count on errno's being the same from one unix to another which is why you need to use these defines when checking for specific errors. Never hard-code numeric errno values into your code. It worked out for me this time, but it won't necessarily every time).
ECONNREFUSED means that there was a machine listening at the specified IP address, but that no process was listening for connections on the specified port number. Either the remote process is not running, it is not binding or accepting connection properly, or it potentially could be blocked by some sort of firewall.
In any case, this points to a problem with the server.
So, check to make sure your remote process is actually ready to accept the connection. You can use telnet or netcat as a test client to see if other client programs that are known to work are able to connect to your server.
Also, I notice that your variable port_no is not declared, so we have no way of knowing what port you are trying to connect to.. but make sure that this variable is of the correct type and has the correct value for the service you are trying to connect to. If port_no doesn't specify the correct port you will get the same type of error. | unknown | |
d16121 | val | The sequence you're referencing in your trigger doesn't exist.
If you use double-quotes around the identifier in your CREATE SEQUENCE statement
CREATE SEQUENCE "seq_employee_id" MINVALUE 1 MAXVALUE 9999 INCREMENT BY 1
START WITH 1 NOCACHE ORDER NOCYCLE ;
then you are creating a case-sensitive identifier. If you do that, you would need to refer to the identifier using double quotes and with the correct case every time you refer to it. That's generally rather annoying which is why I'd never suggest creating case-sensitive identifiers.
SELECT "seq_employee_id".NEXTVAL
INTO :NEW.employee_id
FROM sys.dual;
Starting with 11g, you can simplify the statement by doing a direct assignment of the sequence
:new.employee_id := "seq_employee_id".nextval;
Realistically, I'd suggest recreating the sequence without the double-quotes and using the direct assignment to the :new.employee_id. | unknown | |
d16122 | val | Try to use paramiko module.
Check here for connect function in paramiko which has key_filename argument.
In paramiko module, there is SFTP command which you can use to transfer file.
Check here for SFTP info.
Demo code will looks like below:
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(<IP Address>, username=<User Name>, key_filename=<.PEM File path)
# Setup sftp connection and transmit this script
#print "copying"
sftp = client.open_sftp()
sftp.put(<Source>, <Destination>)
sftp.close()
**
OR
**
You can execute above command directly using python directly.
Please check this link how to execute command in python.
Demo code:
from subprocess import call
cmd = 'scp -i aKey.pem aFile.txt ec2-user@serverIp:folder'
call(cmd.split()) | unknown | |
d16123 | val | Why not make use of [self.collectionView indexPathsForSelectedItems]; . I have done this for deleting multiple images at a time.
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (alertView == deletePhotoConfirmAlert) {
if (buttonIndex == 1) {
// Permission to delete the button is granted here.
NSArray *selectedItemsIndexPaths = [self.collectionView indexPathsForSelectedItems];
// Delete the items from the data source.
[self deleteItemsFromDataSourceAtIndexPaths:selectedItemsIndexPaths];
// Now delete the items from the collection view.
[self.collectionView deleteItemsAtIndexPaths:selectedItemsIndexPaths];
}
}
}
// This method is for deleting the selected images from the data source array
-(void)deleteItemsFromDataSourceAtIndexPaths:(NSArray *)itemPaths {
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSIndexPath *itemPath in itemPaths) {
[indexSet addIndex:itemPath.row];
}
[self.images removeObjectsAtIndexes:indexSet]; // self.images is my data source
}
Edit
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSArray *indexpaths = [self.collectionView indexPathsForSelectedItems];
DetailViewController *dest = [segue destinationViewController];
dest.imageName = [self.images objectAtIndex:[[indexpaths objectAtIndex:0] row]];
} | unknown | |
d16124 | val | You need to configure kestrel to bind requests from 0.0.0.0 instead of localhost to accept requests from everywhere.
You can achieve this with different methods.
1- Run application with urls argument
dotnet app.dll --urls "http://0.0.0.0:5000;https://0.0.0.0:5001"
2- Add kestrel config to appsettings.json (Or any other way that you can inject value to IConfiguration)
{
...
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://0.0.0.0:5000"
},
"Https": {
"Url": "https://0.0.0.0:5001"
}
}
}
...
}
3- Hard-code your binding in the program.cs file.
and the result should look like this
For complete details, please visit
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints | unknown | |
d16125 | val | Here are a few things I would change:
$now=date("Y-m-d g:i:s");
$current_time=strtotime($now);
This can be reduced to simply:
$current_time = time();
For your cron script:
$now=date("Y-m-d g:i:s");
$currentTime=strtotime($now);
$timeAfterOneHour=$currentTime+60*60;
$new_hr=date("Y-m-d g:i:s",$timeAfterOneHour);
Can be changed to:
$currentTime = time();
$timeAfterOneHour=$currentTime+60*60;
$new_hr=date("Y-m-d H:i:s",$timeAfterOneHour);
Notice the H instead of g in the date() format? That's because times are easier to compare if you use a 24hr clock with leading zeroes. | unknown | |
d16126 | val | How do I initialize the base class inside the constructor?
You may not.
The base part of the instance must be initialised before the derived part of the instance or any of its members.
How do I change an FLTK Fl_Window's caption after initialising it?
The documentation says you can call:
label("my caption")
What's wrong with that?
Any other way out of this mess?
No.
Also, you should upgrade to FLTK 2. | unknown | |
d16127 | val | It means you don't have the same repositories activated on both machines. Comparing the output of
zypper lr -u
on both machines should show you which repository to add or enable. | unknown | |
d16128 | val | To achieve expected result, use below option
function addElem() {
var mElem = document.querySelector('.mg_post_description')
var hElems = document.getElementsByTagName('H3');
var node = document.createElement("P");
for (var i = 0; i < hElems.length; i++) {
var textnode = document.createTextNode(hElems[i].innerHTML);
var cloneElem = node.cloneNode(true);
cloneElem.appendChild(textnode);
mElem.appendChild(cloneElem);
}
};
addElem()
Codepen- https://codepen.io/nagasai/pen/YVEzdJ
A:
var d = document.querySelector('.desc'),
h = document.querySelectorAll('.main h3');
h.forEach(function(n) {
var p = document.createElement('p');
p.innerHTML = n.cloneNode(true).innerHTML || '';
d.append(p);
});
.desc {
color: red;
}
<div class="main">
<h3>First</h3>
<h3>Second</h3>
<h3>Third</h3>
</div>
<div class="desc">
</div> | unknown | |
d16129 | val | Whether a menu item is enabled is stored as part of a menu item's state information. The following function reports, whether a menu item (identified by ID) is enabled:
bool IsMenuItemEnabled( HMENU hMenu, UINT uId ) {
UINT state = GetMenuState( hMenu, uId, MF_BYCOMMAND );
return !( state & ( MF_DISABLED | MF_GRAYED ) );
}
A few notes on the implementation:
*
*A menu item can have both MF_DISABLED and MF_GRAYED states. A disabled item looks just like an enabled item, but is otherwise inactive. Neither disabled nor grayed items can be selected.1)
*The MF_ENABLED state equates to 0. As a consequence, it cannot be tested directly, but an expression must be used instead (see GetMenuState).
For completeness, here's an implementation using the newer API (GetMenuItemInfo). Both implementations are functionally identical:
bool IsMenuItemEnabled( HMENU hMenu, UINT uId ) {
MENUITEMINFO mii = { 0 };
mii.cbSize = sizeof( mii );
mii.fMask = MIIM_STATE;
GetMenuItemInfo( hMenu, uId, FALSE, &mii );
return !( mii.fState & MFS_DISABLED );
}
1)The distinction between grayed and disabled items is documented under About Menus: Enabled, Grayed, and Disabled Menu Items. This distinction is no longer exposed in the newer APIs (see MENUITEMINFO), where both MFS_DISABLED and MFS_GRAYED have the same value. | unknown | |
d16130 | val | As Makoto says, it looks like you have started CherryPy twice. Are you calling both engine.start/engine.block along with cherrypy.quickstart? If so, remove one or the other.
A: My Problem was the usage of and old version (actually the latest one linked on their site!) of cherrypy in conjunction with python 3.3. Taking the latest packages from bitbucket solved this for me! | unknown | |
d16131 | val | i've figured out the answer.
*
*i am using GridView to display the images. just changes the adapter to change the content
*this question doesn't have to be answered.
*same as answer no. 1. the code is like choosepic.xml that i post before.
and the problem why my `GridView is not displayed images, coz getCount() in ImageAdapter is return 0, so no images is displayed in GridView.
i changed return 0; with return animalValues.size() | unknown | |
d16132 | val | Here is an O(n) solution using collections.defaultdict:
from collections import defaultdict
dd = defaultdict(list)
for (key1, key2), value in zip(a, b):
dd[(key1, key2)].append(value)
aa = list(map(list, dd))
bb = list(map(min, dd.values()))
print(aa, bb, sep='\n'*2)
[[9, 5], [9, 10000], [5, 10000], [10001, 10]]
[19144.85, 8824.73, 23348.02, 40188.8]
Explanation
There are 3 steps:
*
*Create a dictionary mapping each pair of keys to a list of values. Be careful to use tuple as keys, which must be hashable.
*For unique keys, just extract your defaultdict keys, mapping to list so that you have a list of lists instead of list of tuples.
*For minimum values, use map with min.
Note on ordering
Dictionaries are insertion ordered in Python 3.6+, and this can be relied upon in 3.7+. In earlier versions, you can rely on consistency of ordering between dd.keys and dd.values provided no operations have taken place in between access of keys and values. | unknown | |
d16133 | val | I am also trying to update an APO which have been developed for W7/8 to the new format introduced by W8.1, however it doesn't seem like much documentation has been released yet.
What I have found so far, is that Windows 8.1 requires some new methods for discovery and control of effects to be implemented into the APO. This means that Skype would be able to discover certain APO effects and disable them if it needs to.
The new interface IAudioSystemEffects2:
link
Some updated code can be found in the new SwapAPO example:
link
Not much, but hopefully it can help you get going in the right direction. | unknown | |
d16134 | val | As the first answer notes, this may not be a good idea on big XML documents. The simplest and most portable code for PHP 5.1.2 and above may be to use SimpleXML. It may have been built in to earlier PHP versions, but it is standard after 5.1.2.
<?php
$file = 'http://www.gostanford.com/data/xml/events/m-baskbl/2010/index.xml';
$xml = simplexml_load_file($file);
if ($xml === false) {
echo "Couldn't load file\n";
exit (1);
}
$xmlArray = array();
foreach ($xml as $event_date) $xmlArray[] = $event_date;
$xmlArray = array_reverse($xmlArray);
foreach ($xmlArray as $event_date) {
if(!empty($event_date->event['vn']) && !empty($event_date->event['hn']) && !empty($event_date->event['vs']) && !empty($event_date->event['hs']))
{
echo '<li>';
echo '<h3>', $event_date->event['vn'], ' vs ', $event_date->event['hn'], '</h3>';
echo '<p><strong>', $event_date->event['vs'], ' - ', $event_date->event['hs'], '</strong></p>';
echo '<p>', $event_date['date'], '</p>';
echo '<p>', $event_date->event['local_time'], '</p>';
echo '</li>';
}
}
?>
A: If $xml is just an array, you can use array_reverse($xml) to reverse it:
foreach (array_reverse($xml) as $event_date) {
// etc
}
But, if it's long, that might not be efficient. You could use a manual for-loop with decrementing indices:
for ($i = sizeof($xml) - 1; $i >= 0; --$i) {
// use $xml[$i] to access each element
}
A: Obviously you can read your xml to an array and print in reverse order. However, this might not be a good idea for a long list.
EDIT:
foreach($xml as $event_date){
if(!empty($event_date->event['vn']) && !empty($event_date->event['hn']) && !empty($event_date->event['vs']) && !empty($event_date->event['hs']))
{
$my[]=array (
"vn" => $event_date->event['vn'],
"hn" => $event_date->event['hn']
...
);
}
}
for($i=count($my)-1;$i>=0;$i--) {
echo '<li>';
echo '<h3>', $my[$i]['vn'], ' vs ', $my[$i]['hn'];
...
echo '</li>';
}
Hope this helps, it might need fixes.
A: Can you reverse your output instead of the xml? IE:
$arr = array();
foreach($xml as $event_date){
if(!empty($event_date->event['vn']) && !empty($event_date->event['hn']) && !empty($event_date->event['vs']) && !empty($event_date->event['hs']))
{
$strLine = "";
$strLine .= '<li>';
$strLine .= '<h3>'. $event_date->event['vn']. ' vs '. $event_date->event['hn']. '</h3>';
$strLine .= '<p><strong>'. $event_date->event['vs']. ' - '. $event_date->event['hs']. '</strong></p>';
$strLine .= '<p>'. $event_date['date']. '</p>';
$strLine .= '<p>'. $event_date->event['local_time']. '</p>';
$strLine .= '</li>';
$arr[] = $strLine;
}
}
$arr = array_reverse($arr);
foreach ($arr as $line)
{
echo $line;
} | unknown | |
d16135 | val | As you can see if you do View Source in Firefox, the items you're looking for aren't in the original HTML markup sent by the server. In fact, they are added by a JavaScript after the page has loaded. Mechanize doesn't run JavaScript, so it can't see those items; it only sees what's in the HTML.
As an aside, this completely unnecessary use of JavaScript is a plague on modern Web development and makes doing things like you're trying to do much harder than they should be. (But then, maybe that's why they do it.)
Anyway, to scrape that information from the page, you need to use something that actually loads the page in a real Web browser, such as Selenium.
The other SO question you linked is different because the targeted site actually sends an HTTP POST when you select from the menus, and receives a whole new HTTP page back. This page doesn't do that. | unknown | |
d16136 | val | var formData = new FormData();
formData.append("file-identifier", $('#file-identifier').get(0).files[0]);
formData.append("variable", $.session.get("variable"));
$.ajax({
url : "path/to/file.file",
type : "POST",
processData: false,
contentType: false,
data : formData,
dataType: "json",
success : function(data){
//handle on success
},
error : function(jqXHR, textStatus, errorThrown){
console.log(arguments);
}
});
This is a sample from a script I used recently to upload a jpeg and a variable taking content from a session variable. Appending these to a FormData object allows you to transfer both file and variable in one request. | unknown | |
d16137 | val | why not do this?
<div>
<a href="http://www.google.com"><img src="http://blog.caranddriver.com/wp-content/uploads/2016/01/BMW-i8-Mirrorless-cameras-101-876x535.jpg" width="400" alt="img" /></a>
</div> | unknown | |
d16138 | val | You can change aggregatetion for grouping by datetimes only:
cases.groupby(['ObservationDate'])['Confirmed'].sum().plot()
Or if need summed values per ObservationDate and Country/Region:
cases.groupby(['Country/Region','ObservationDate'])['Confirmed'].sum().unstack(0).plot() | unknown | |
d16139 | val | I'm not sure what all you're doing, but since somefile.txt is in the same folder as module.py, you could make the path to it relative to the module by using its predefined __file__ attribute:
import os
fileToRead = os.path.join(os.path.dirname(__file__), "somefile.txt") | unknown | |
d16140 | val | var r1 = 15;
var q = from t in Context.Table1
where t.Reg1 == r1 &&
t.Reg2 == Context.Table2
.Where(t2 => t2.Reg1 == r1)
.Max(t2 => t2.Reg2)
select t;
Easier still if you have a navigation/association from Table1 to Table2. But you didn't show that, so neither will I.... | unknown | |
d16141 | val | You can try this:
DateTime elapsedTime = DateTime.utc(0);
print(elapsedTime);
elapsedTime = elapsedTime.add(Duration(seconds: 1));
print(elapsedTime);
Note: The lowest value for day and month is 1 and not 0. | unknown | |
d16142 | val | Just use az cli rest to assign a custom app role to a principal via Azure AD Graph Rest API :
az rest --method post --uri "https://graph.windows.net/<your tenant ID>/servicePrincipals/<your principle object Id>/appRoleAssignments?api-version=1.6" --body "{\"id\":\"<your custom role app ID>\",\"principalId\":\"<your principle object Id>\",\"resourceId\":\"<your app object id>\"}" --headers "Authorization=Bearer <access token>"
You can get access token via az account get access token :
az account get-access-token --resource "https://graph.windows.net"
Test request on Azure cli :
Result, as you can see the role has been assigned to principle successfully : | unknown | |
d16143 | val | Stupid mistake...I changed a variable name and didntt change it in the query... link_icon_fk = '$link_icon_fk' should have been link_icon_fk = '$icon' - trying to work too fast... | unknown | |
d16144 | val | The C++ synchronization mechanisms are designed to C++ principles. They free their resources in the destructor, and they also use RAII to ensure safe locking. They use exceptions to signal errors.
Essentially, they are much harder to use incorrectly than the function-based native Windows API. This means that if you can use them (your implementation supports them), you always should use them.
Oh, and they are cross-platform.
A: One consideration should be what your compiler can handle. For example, when you install MinGW on Windows, you can choose whether to install the API for POSIX threads or Win32 threads. On the other hand, if you use TDM-GCC, you should be aware that versions 4.7.1 and lower use Win32 threads, while versions 4.8.1 and higher use POSIX threads. And as woolstar mentioned above, if you're using Microsoft's compiler, you should check to see whether the bugs in its support for these classes have been worked out.
If your compiler supports POSIX threads, you can use the C++ thread classes of the Standard Library (e.g. thread, mutex, condition_variable). If your compiler supports Win32 threads, you can use the Win32 thread functions.
In my case, I originally had TDM-GCC 4.7.1 and tried to use the C++ Standard Library classes, but that didn't work (for reasons explained above). So I installed MinGW by itself and chose "posix" in the "threads" option of the installer. Then I was able to use those classes. | unknown | |
d16145 | val | try this
private int stopPosition;
private VideoView splashVideoView; <-- my Video view
in onCreate
//video player
if (savedInstanceState != null) {
stopPosition = savedInstanceState.getInt("position");
}
@Override
protected void onResume() {
super.onResume();
splashVideoView.seekTo(stopPosition);
splashVideoView.start();
}
// This gets called before onPause so pause video here.
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
stopPosition = splashVideoView.getCurrentPosition();
splashVideoView.pause();
outState.putInt("position", stopPosition);
}
A: try this
private int videoViewStopPosition ;
@Override
protected void OnPause(){
super.onPause();
videoViewStopPosition = vidView.getCurrentPosition();
vidView.pause();
}
@Override
protected void OnResume() {
super.onResume();
vidView.seekTo(videoViewStopPosition);
vidView.start();
}
A: I had the same issue. I found that the main reason for that was the use of FrameLayout as the parent layout. I changed it into RelativeLayout as parent layout of the VideoView and the problem get solved.
A: You need to create Video view in onResume() also. Try this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
setVideoBackground();
}
@Override
protected void onResume() {
super.onResume();
setVideoBackground();
}
private void setVideoBackground(){
video = (VideoView) findViewById(R.id.video);
// Load and start the movie
Uri video1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videoplayback);
video.setVideoURI(video1);
video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
video.start();
} | unknown | |
d16146 | val | Firstly you should explain more about your situation. As @mico has told here is a solution:
<filter>
<filter-name>Jersey Filter</filter-name>
<filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>your package name(s)</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
<param-value>.*\.jsp|.*\.css|.*\.png|.*\.js|.*\.gif|.*\.jpg</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Jersey Filter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
The idea on solution based on:
defining Jersey ServletContainer as a filter instead of a servlet
Here you can read more: http://jersey.576304.n2.nabble.com/Tomcat-trailing-slashes-and-welcome-files-td4684494.html
Here says that: If you have a '/*' mapping, then Tomcat won't redirect
One more: you should see how tomcat logs your request and decide the main problem. | unknown | |
d16147 | val | Simply make your information button float above the scroll view by adding it to the scroll view's superview, then ordering the views such that the information button resides on top of the scroll view. You'll retain scrolling capability, while still catching button touches. | unknown | |
d16148 | val | No. Consider:
void f(Base* ptr) {
// What type does ptr point to?
// The runtime derived type might not exist when this function compiles
}
Since the dynamic type of the pointer is only know at runtime, it's impossible for the compiler to gain access to it when compiling the function.
If the definition is available there may be some more options, but all of them require you knowing in advance the entire set of types you intend to support, and possibly need to downcast to first. (A type "id" might help if you go this route.)
You might be able to build some limited working designs with a visitor pattern. | unknown | |
d16149 | val | When node.js spawns a forked environment, it doesn't copy over your user's environment variables. You will need to do that manually.
You will need to get JAVA_HOME from process.env and set it in your exec() call.
Something like this should work:
var config = {
env: process.env
};
exec('javacmd', config,
function() {
console.log(arguments);
});
Or if you wanted to be more explicit, you could extract only the variables you needed (JAVA_HOME, etc) from process.env
See here for more details:
How to exec in NodeJS using the user's environment?
A: Just uninstall node js and re install node js. Its solve my problem. | unknown | |
d16150 | val | The content you're attempting to scrape appears to be populated by JS after the page loads. To see for yourself, inspect the content of div#flight_results of the document you're currently parsing:
url = 'http://www.momondo.com/multicity/?Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false#Search=true&TripType=oneway&SegNo=1&SO0=KUL&SD0=KBR&SDP0=31-12-2012&AD=2&CA=0,0&DO=false&NA=false'
doc = Nokogiri::HTML(open(url))
doc.at_css('div#flight_results').to_html #=> '<div id="flight_results"></div>'
Though it is outside of the scope of this question, you can generally reconstruct the JS requests used to populate the content you're after. | unknown | |
d16151 | val | jQuery uses its _determineDate() function to calculate the minDate date object based on its attribute. I modified its behaviour and made a function. Note that it only deals with the "offset" type of values and nothing else.
/* minDateAttr is the minDate option of the datepicker, eg '+1d +3m' */
function getMinDate(minDateAttr) {
var minDate = new Date();
var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
var matches = pattern.exec(minDateAttr);
while (matches) {
switch (matches[2] || 'd') {
case 'd' : case 'D' :
minDate.setDate(minDate.getDate() + parseInt(matches[1],10));
break;
case 'w' : case 'W' :
minDate.setDate(minDate.getDate() + parseInt(matches[1],10) * 7);
break;
case 'm' : case 'M' :
minDate.setMonth(minDate.getMonth() + parseInt(matches[1],10));
break;
case 'y': case 'Y' :
minDate.setYear(minDate.getFullYear() + parseInt(matches[1],10));
break;
}
matches = pattern.exec(minDateAttr);
}
return minDate;
}
I originally planned on answering the following, but came up with a (better) solution - the one above. However, I'm going to include it, in case it's needed for debugging reasons etc.
The _determineDate() function is technically availible for use, but it's not supposed to be used and may change in the future. Nevertheless, this would be how to use it:
var minDateAttr = $(elem).datepicker("option", "minDate");
var inst = $(elem).data("datepicker");
var minDateObj = $.datepicker._determineDate(inst, minDateAttr, new Date());
A: This update fixes a few bugs surrounding month calculation bugs, hours and leap years. Big props to Simen for the first version which was the foundation.
Also this version will allow for optional second param dateVal where you can pass a date to calculate from instead of using today's date.
function determineDate(dateAttr, dateVal) {
var date = dateVal === undefined ? new Date() : new Date(dateVal);
var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
var matches = pattern.exec(dateAttr);
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
while (matches) {
switch (matches[2] || 'd') {
case 'd' : case 'D' :
day += parseInt(matches[1],10); break;
case 'w' : case 'W' :
day += parseInt(matches[1],10) * 7; break;
case 'm' : case 'M' :
month += parseInt(matches[1],10);
day = Math.min(day, getDaysInMonth(year, month));
break;
case 'y': case 'Y' :
year += parseInt(matches[1],10);
day = Math.min(day, getDaysInMonth(year, month));
break;
}
matches = pattern.exec(dateAttr);
}
var newdate = new Date(year, month, day);
newdate.setHours(0);
newdate.setMinutes(0);
newdate.setSeconds(0);
newdate.setMilliseconds(0);
return daylightSavingAdjust(newdate);
}
function daylightSavingAdjust(date){
if (!date){
return null;
}
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return date;
}
function getDaysInMonth(year, month){
return 32 - daylightSavingAdjust(new Date(year, month, 32)).getDate();
} | unknown | |
d16152 | val | char ***res = malloc(sizeof(char **));
res[0] = malloc(sizeof(char *) * len);
memcpy(&res[0], arr, len);
The first line allocates space for a single char ** and makes res point at it
The second line allocates space for an array of len pointers to char and makes res[0] point at it.
The third line copies len byes from arr over the top of the memory pointed at by res, overwriting the result of the second malloc call and then scribbling over memory after the block allocated by the first malloc call.
You probably actually want something like
mempy(res[0], arr, len * sizeof(char*));
which will copy an array of len pointers (pointed at by arr) into the memory allocated by the second malloc call.
A: If this is an array of C strings that you need deep copied:
char** array_deep_copy(char **arr, int len) {
// calloc() makes "allocation of N" calculations more clear
// that this is N allocations of char* becoming char**
char **res = calloc(len, sizeof(char*));
for (int i = 0; i < len; ++i) {
// Use strdup() if available
res[i] = strdup(arr[i]);
}
return res;
}
Note that this needs a proper release function that will go through and recursively free() those cloned strings or this leaks memory.
If you only need a shallow copy:
char** array_shallow_copy(char **arr, int len) {
char **res = calloc(len, sizeof(char*));
// memcpy(dest, src, size) is usually more efficient than a loop
memcpy(res, arr, sizeof(char*) * len);
return res;
}
This one doesn't need a recursive free(), you can just free() the top-level pointer and you're done. This one shares data with the original, so if any of those pointers are released before this structure is then you'll have invalid pointers in it. Be careful! | unknown | |
d16153 | val | For loop can be used as well
#!/bin/bash
Directories=( /dir1 /dir2 /dir3)
for dir in "${Directories[@]}"
do
cd "${dir}"
done
A: Update: In fact, the solution below is not suitable for commands meant to alter the current shell's environment, such as cd. It is suitable for commands that invoke external utilities.
For commands designed to alter the current shell's environment, see Balaji Sukumaran's answer.
xargs is the right tool for the job:
printf '%s\n' "${Directories[@]}" | xargs -I % <externalUtility> %
*
*printf '%s\n' "${Directories[@]}" prints each array element on its own line.
*xargs -I % <externalUtility> % invokes external command <externalUtility> for each input line, passing the line as a single argument; % is a freely chosen placeholder. | unknown | |
d16154 | val | You are facing a same origin policy issue.
This is because your client-side (web browser) application is fetched from Server-A, while it tries to interact with data on Server-B.
*
*Server-A is wherever you application is fetched from (before it is displayed to the user on their web browser).
*Server-B is localhost, where your mock service is deployed to
For security reasons, by default, only code originating from Server-B can talk to Server-B (over-simplifying a little bit). This is meant to prevent malicious code from Server-A to hijack a legal application from Server-B and trick it into manipulating data on Server-B, behind the user's back.
To overcome this, if a legal application from Server-A needs to talk to Server-B, Server-B must explicitly allow it. For this you need to to implement CORS (Cross Origin Resource Sharing) - Try googling this, you will find plenty of resources that explain how to do it. https://www.html5rocks.com/en/tutorials/cors/ is also a great starting point.
However, as your Server-B/localhost service is just a mock service used during development and test, if your application is simple enough, you may get away with the mock service simply adding the following HTTP headers to all its responses:
Access-Control-Allow-Origin:*
Access-Control-Allow-Headers:Keep-Alive,User-Agent,Content-Type,Accept [enhance with whatever you use in you app]
As an alternative solution (during dev/tests only!) you may try forcing the web browser to disregard the same origin policy (eg: --disable-web-security for Chrome) - but this is dangerous if you do not pay attention to use separate instances of the web browser for your tests and for you regular web browsing. | unknown | |
d16155 | val | I think it is better to use Mobicents jSS7
A: You can use lk-sctp in combination with Netty framework over jdk-7 (and above) to implement M3UA (RFC 4666).
Netty-4.0.25-FINAL is stable version for SCTP support.
So the combination is:
*
*SCTP stack : lk-sctp-1.0.16 (over Red Hat Enterprise Linux Server release 6.5 (Santiago))
*JDK-7 or above
*Netty-4.0.25-FINAL
And your application on top of it.
A sample code for SCTPClientHandler can be:
public class SctpClientHandler extends ChannelDuplexHandler {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
throws Exception {
SctpChannel sctpChannel = (SctpChannel) ctx.channel();
if (evt instanceof AssociationChangeNotification) {
AssociationChangeNotification associationChangeNotification = (AssociationChangeNotification) evt;
switch (associationChangeNotification.event()) {
case CANT_START:
//Do something
break;
case COMM_LOST:
//
case COMM_UP:
} else if (evt instanceof PeerAddressChangeNotification) {
PeerAddressChangeNotification peerAddressChangeNotification = (PeerAddressChangeNotification) evt;
int associationId = sctpChannel.association().associationID();
switch (peerAddressChangeNotification.event()) {
case ADDR_ADDED:
}
} else if (evt instanceof SendFailedNotification) {
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
SctpMessage sctpMessage = (SctpMessage) msg;
// Check if this is a M3UA message
if (sctpMessage.protocolIdentifier() == 3) {
// Send upstream - to M3UA
ctx.fireChannelRead(sctpMessage);
}
}
public void send(ByteBuf buffer, int streamId) {
SctpMessage message = new SctpMessage(3, streamId, buffer);
ctx.writeAndFlush(message);
}
public void send(ByteBuf buffer, int streamId, SocketAddress remoteAddress) {
MessageInfo msgInfo = MessageInfo.createOutgoing(remoteAddress,
streamId);
SctpMessage message = new SctpMessage(msgInfo, buffer);
ctx.writeAndFlush(message);
}
public void send(ByteBuf buffer, int streamId, boolean unOrderedFlag) {
SctpMessage message = new SctpMessage(3, streamId, buffer);
message.messageInfo().unordered(unOrderedFlag);
ctx.writeAndFlush(message);
}
public void send(ByteBuf buffer, int streamId, SocketAddress remoteAddress,
boolean unOrderedFlag) {
MessageInfo msgInfo = MessageInfo.createOutgoing(remoteAddress,
streamId);
msgInfo.unordered(unOrderedFlag);
SctpMessage message = new SctpMessage(msgInfo, buffer);
ctx.writeAndFlush(message);
}
}
SCTPServerHandler can also be created as above.
For initializing Bootstrap:
bootstrap.group(worker)
.channel(NioSctpChannel.class)
.option(SctpChannelOption.SCTP_NODELAY,true)
.handler(new ChannelInitializer<SctpChannel>() {
@Override
public void initChannel(SctpChannel ch) throws Exception {
ch.pipeline().addLast(
new SctpClientHandler());
ch.pipeline().addLast(new M3UAAspHandler());
}
});
This combination scales a lot as well. Happy coding. | unknown | |
d16156 | val | My recommendation would be to restructure your repeat statement like this...
set done to false
repeat while not done
if reCaptcha = "something" then
set done to true
end if
end repeat | unknown | |
d16157 | val | You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to combine the Entity Framework 4 with MVVM. | unknown | |
d16158 | val | Exactly what the error is saying
p.PhoneNumberId equals link.PhoneNumberId
should be
link.PhoneNumberId equals p.PhoneNumberId
Full code
var query = (from u in myEntities.Users
join link in myEntities.linkUserPhoneNumbers on u.UserId equals link.UserId
join p in myEntities.PhoneNumbers on link.PhoneNumberId equals p.PhoneNumberId
where u.UserName == Username && u.Password == Password
select u).ToList(); | unknown | |
d16159 | val | I think you can use an extension method like this:
public static class MyExtensions
{
public static int[] GetValues(this Array source, int x, int y)
{
var length = source.GetUpperBound(2);
var values = new int[length+1];
for (int i = 0; i < length+1; i++)
{
values[i] = (int)source.GetValue(x, y, i);
}
return values;
}
}
Usage:
int[,,] mainArray = new int[10,10,3];
int[] sub = mainArray.GetValues(0, 1);
A: You could use nested arrays instead.
// Initialization
int[][][] mainArray = new int[10][][];
for (int i = 0; i < mainArray.Length; i++)
{
mainArray[i] = new int[10][];
for (int j = 0; j < mainArray[i].Length; j++)
{
mainArray[i][j] = new int[3];
}
}
// Usage
int[] sub = mainArray[0][1];
Yes, the initialization is a bit more complex, but other than that it's all the same. And nested arrays even have better performance (but you shouldn't care about array performance unless your profiler told you so).
Here is a helper class I wrote to help with the initialization of nested arrays.
public static class NestedArray
{
public static Array Create<T>(params int[] lengths)
{
Type arrayType = typeof(T);
for (int i = 0; i < lengths.Length - 1; i++)
arrayType = arrayType.MakeArrayType();
return CreateArray(arrayType, lengths[0], lengths.Skip(1).ToArray());
}
private static Array CreateArray(Type elementType, int length, params int[] subLengths)
{
Array array = Array.CreateInstance(elementType, length);
if (subLengths.Length > 0)
{
for (int i = 0; i < length; i++)
{
Array nestedArray = CreateArray(elementType.GetElementType(), subLengths[0], subLengths.Skip(1).ToArray());
array.SetValue(nestedArray, i);
}
}
return array;
}
}
Usage:
int[][][] mainArray = (int[][][])NestedArray.Create<int>(10, 10, 3);
Full commented source code can be found in this gist.
A: You can use Buffer.BlockCopy and some math, if you always want the the last dimension:
Buffer.BlockCopy(mainArray, (D2*i+j)*D3*sizeof(TYPE), sub, 0, D3*sizeof(TYPE));
will put mainArray[i,j,] in sub, where D1, D2, and D3 are your dimensions and TYPE is the type of the array elements. | unknown | |
d16160 | val | To deal with the original issue and cope with deletions of multiple rows your trigger could be rewritten as follows.
ALTER TRIGGER [dbuser].[trig_SiteMaptenSil] ON [dbuser].[Articles]
AFTER DELETE
AS
BEGIN
SET NOCOUNT ON
DELETE
FROM s
FROM dbuser.SiteMap AS s
INNER JOIN Deleted AS d
ON s.Url = N'~/c.aspx?g=' + CONVERT(nvarchar(5), d.CategoryId) + N'&k='
+ CONVERT(nvarchar(36), d.ArticleId)
END | unknown | |
d16161 | val | Change your code to:
$(".asset-container").mouseover(function() {
var id = $(this).children("video").data("id");
$(this).parent().children('.popover-content[data-id=' + id + ']').show();
}); | unknown | |
d16162 | val | Please take a look at the CellTitle example. It creates a PDF in which titles are added on the cell border: cell_title.pdf
This is accomplished by using a cell event:
class Title implements PdfPCellEvent {
protected String title;
public Title(String title) {
this.title = title;
}
public void cellLayout(PdfPCell cell, Rectangle position,
PdfContentByte[] canvases) {
Chunk c = new Chunk(title);
c.setBackground(BaseColor.LIGHT_GRAY);
PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS];
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
new Phrase(c), position.getLeft(5), position.getTop(5), 0);
}
}
A cell event can be added to a PdfPCell using the setCellEvent() method:
public PdfPCell getCell(String content, String title) {
PdfPCell cell = new PdfPCell(new Phrase(content));
cell.setCellEvent(new Title(title));
cell.setPadding(5);
return cell;
}
Next time, please show what you've tried before asking a question. Also take a look at the official documentation because everything you needed to answer your question yourself was available on the iText web site. | unknown | |
d16163 | val | Something like this?
void main() {
getMonthAYearFromCurrent().forEach(print);
// August 2021
// July 2021
// June 2021
// May 2021
// April 2021
// March 2021
// February 2021
// January 2021
// December 2020
// November 2020
// October 2020
// September 2020
}
List<String> getMonthAYearFromCurrent({int length = 12}) {
const listOfMonth = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
final currentDate = DateTime.now();
final months = <String>[];
for (var i = 0; i < length; i++) {
final yearInt = currentDate.year - (0 - (currentDate.month - i) + 12) ~/ 12;
final monthInt = (currentDate.month - i - 1) % 12;
months.add('${listOfMonth[monthInt]} $yearInt');
}
return months;
} | unknown | |
d16164 | val | I highly suggest you look into the Handle object and in particular the postDelayed method. That way you can keep everything on the UI thread while not causing the thread to actually be tied up in an animate method. This also keeps the Activity from giving that dreaded this-application-is-not-responding message.
In fact, simply wrapping your calls to the control's setters in a runnable and passing them to postDelayed should be enough to update the GUI controls.
[Update]
As an example per your comments you might try something like this. I haven't actually tested this but I think the idea is still there...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ToggleButton btn1 = (ToggleButton) findViewById(R.id.btn1);
final ToggleButton btn2 = (ToggleButton) findViewById(R.id.btn2);
// more btns
Handler handler = new Handler();
/* tell the handler run these bits after 1 sec, 2 sec, 3 sec, ect... */
handler.postDelayed(new Runnable() { void run () { btn1.requestFocus(); } }, 1000);
handler.postDelayed(new Runnable() { void run () { btn2.requestFocus(); } }, 2000);
handler.postDelayed(new Runnable() { void run () { btn2.setChecked(true); } }, 3000);
} | unknown | |
d16165 | val | model.predict() executes the actual prediction. You can't predict on placeholders, you need to feed that function real data. If you explicitly feed it None for input data, then the model must have been created with existing data tensor(s), and it still is what executes the actual prediction.
Normally, when a model is created, it has placeholder tensors for the input and output. However, you have the option of giving it real tensors, instead of placeholders. See an example of this here. In this case, and only this case, you can use fit, predict, or evaluate without feeding it data. The only reason you can do that is because the data already exists. | unknown | |
d16166 | val | OK, however. My workaround is to change the view hierarchy and set the UIImageView behind the UINavigationItem. Seems to work. | unknown | |
d16167 | val | If there are no gaps in the range, just use the starting value...
# data.yml
0: 5
51: 9
101: 13
and then your method...
def get_debt_for_month(api_request_count)
thresholds = YAML.load_file('data.yml')
thresholds.sort.select{|e| e[0] <= api_request_count}.last[1]
end | unknown | |
d16168 | val | If you don't want to repeat this a lot, just create a helper function, like this:
public static class DataReaderExtensions
{
public static string GetStringOrNull(this IDataReader reader, int ordinal)
{
return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
}
public static string GetStringOrNull(this IDataReader reader, string columnName)
{
return reader.GetStringOrNull(reader.GetOrdinal(columnName));
}
}
Which you can call like this:
value = reader.GetStringOrNull(n);
A: That really is the best way to go about it if you wish to avoid any exceptions. You need to decide whether or not a null field represents an exceptional situation in your code - if it doesn't then use this method. If it does then I would suggest that you either allow the exception to be thrown or catch the exception and wrap it in a more meaniful exception and throw that one.
But the main thing to know is that this is the standard way to retrieve values from a data reader when a null field does not represent an exceptional situation in the application domain.
A: This worked for me:
value = reader.GetValue(n).ToString();
A: The code you posted is fine. You could also do something like that :
value = r[n] as string;
If the value in the database is null, r[n] will return DBNull.Value, and the cast to string will return null. | unknown | |
d16169 | val | I know the answer has been accepted already, but want to provide another solution for cases when for some reason SSMS wizard is not able to generate script for triggers (in my case it was MSSQL2008R2)
This solution is based on idea from dana above, but uses 'sql_modules' instead to provide the full code of the trigger if it exceeds 4000 chars (restriction of 'text' column of 'syscomments' view)
select [definition],'GO' from sys.sql_modules m
inner join sys.objects obj on obj.object_id=m.object_id
where obj.type ='TR'
Right click on the results grid and then "Save results as..." saves to file with formatting preserved
A: To script all triggers you can define the stored procedure:
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Procedure:
-- [dbo].[SYS_ScriptAllTriggers]
--
-- Parameter:
-- @ScriptMode bit
-- possible values:
-- 0 - Script ALTER only
-- 1 - Script CREATE only
-- 2 - Script DROP + CREATE
ALTER PROCEDURE [dbo].[SYS_ScriptAllTriggers]
@ScriptMode int = 0
AS
BEGIN
DECLARE @script TABLE (script varchar(max), id int identity (1,1))
DECLARE
@SQL VARCHAR(8000),
@Text NVARCHAR(4000),
@BlankSpaceAdded INT,
@BasePos INT,
@CurrentPos INT,
@TextLength INT,
@LineId INT,
@MaxID INT,
@AddOnLen INT,
@LFCR INT,
@DefinedLength INT,
@SyscomText NVARCHAR(4000),
@Line NVARCHAR(1000),
@UserName SYSNAME,
@ObjID INT,
@OldTrigID INT;
SET NOCOUNT ON;
SET @DefinedLength = 1000;
SET @BlankSpaceAdded = 0;
SET @ScriptMode = ISNULL(@ScriptMode, 0);
-- This Part Validated the Input parameters
DECLARE @Triggers TABLE (username SYSNAME NOT NULL, trigname SYSNAME NOT NULL, objid INT NOT NULL);
DECLARE @TrigText TABLE (objid INT NOT NULL, lineid INT NOT NULL, linetext NVARCHAR(1000) NULL);
INSERT INTO
@Triggers (username, trigname, objid)
SELECT DISTINCT
OBJECT_SCHEMA_NAME(B.id), B.name, B.id
FROM
dbo.sysobjects B, dbo.syscomments C
WHERE
B.type = 'TR' AND B.id = C.id AND C.encrypted = 0;
IF EXISTS(SELECT C.* FROM syscomments C, sysobjects O WHERE O.id = C.id AND O.type = 'TR' AND C.encrypted = 1)
BEGIN
insert into @script select '/*';
insert into @script select 'The following encrypted triggers were found';
insert into @script select 'The procedure could not write the script for it';
insert into
@script
SELECT DISTINCT
'[' + OBJECT_SCHEMA_NAME(B.id) + '].[' + B.name + ']' --, B.id
FROM
dbo.sysobjects B, dbo.syscomments C
WHERE
B.type = 'TR' AND B.id = C.id AND C.encrypted = 1;
insert into @script select '*/';
END;
DECLARE ms_crs_syscom CURSOR LOCAL forward_only FOR
SELECT
T.objid, C.text
FROM
@Triggers T, dbo.syscomments C
WHERE
T.objid = C.id
ORDER BY T.objid,
C.colid
FOR READ ONLY;
SELECT @LFCR = 2;
SELECT @LineId = 1;
OPEN ms_crs_syscom;
SET @OldTrigID = -1;
FETCH NEXT FROM ms_crs_syscom INTO @ObjID, @SyscomText;
WHILE @@fetch_status = 0
BEGIN
SELECT @BasePos = 1;
SELECT @CurrentPos = 1;
SELECT @TextLength = LEN(@SyscomText);
IF @ObjID <> @OldTrigID
BEGIN
SET @LineID = 1;
SET @OldTrigID = @ObjID;
END;
WHILE @CurrentPos != 0
BEGIN
--Looking for end of line followed by carriage return
SELECT @CurrentPos = CHARINDEX(CHAR(13) + CHAR(10), @SyscomText, @BasePos);
--If carriage return found
IF @CurrentPos != 0
BEGIN
WHILE ( ISNULL(LEN(@Line), 0) + @BlankSpaceAdded + @CurrentPos - @BasePos + @LFCR ) > @DefinedLength
BEGIN
SELECT @AddOnLen = @DefinedLength - (ISNULL(LEN(@Line), 0) + @BlankSpaceAdded );
INSERT
@TrigText
VALUES
( @ObjID, @LineId, ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''));
SELECT
@Line = NULL,
@LineId = @LineId + 1,
@BasePos = @BasePos + @AddOnLen,
@BlankSpaceAdded = 0;
END;
SELECT @Line = ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @CurrentPos - @BasePos + @LFCR), N'');
SELECT @BasePos = @CurrentPos + 2;
INSERT
@TrigText
VALUES
( @ObjID, @LineId, @Line );
SELECT @LineId = @LineId + 1;
SELECT @Line = NULL;
END;
ELSE
--else carriage return not found
BEGIN
IF @BasePos <= @TextLength
BEGIN
/*If new value for @Lines length will be > then the
**defined length
*/
WHILE ( ISNULL(LEN(@Line), 0) + @BlankSpaceAdded + @TextLength - @BasePos + 1 ) > @DefinedLength
BEGIN
SELECT @AddOnLen = @DefinedLength - ( ISNULL(LEN(@Line), 0 ) + @BlankSpaceAdded );
INSERT
@TrigText
VALUES
( @ObjID, @LineId, ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''));
SELECT
@Line = NULL,
@LineId = @LineId + 1,
@BasePos = @BasePos + @AddOnLen,
@BlankSpaceAdded = 0;
END;
SELECT @Line = ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @TextLength - @BasePos+1 ), N'');
IF LEN(@Line) < @DefinedLength AND CHARINDEX(' ', @SyscomText, @TextLength + 1) > 0
BEGIN
SELECT
@Line = @Line + ' ',
@BlankSpaceAdded = 1;
END;
END;
END;
END;
FETCH NEXT FROM ms_crs_syscom INTO @ObjID, @SyscomText;
END;
IF @Line IS NOT NULL
INSERT
@TrigText
VALUES
( @ObjID, @LineId, @Line );
CLOSE ms_crs_syscom;
insert into @script select '-- You should run this result under dbo if your triggers belong to multiple users';
insert into @script select '';
IF @ScriptMode = 2
BEGIN
insert into @script select '-- Dropping the Triggers';
insert into @script select '';
insert into @script
SELECT
'IF EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID(''[' + username + '].[' + trigname + ']'')'
+ ' AND ObjectProperty(OBJECT_ID(''[' + username + '].[' + trigname + ']''), ''ISTRIGGER'') = 1)'
+ ' DROP TRIGGER [' + username + '].[' + trigname +']' + CHAR(13) + CHAR(10)
+ 'GO' + CHAR(13) + CHAR(10)
FROM
@Triggers;
END;
IF @ScriptMode = 0
BEGIN
update
@TrigText
set
linetext = replace(linetext, 'CREATE TRIGGER', 'ALTER TRIGGER')
WHERE
upper(left(replace(ltrim(linetext), char(9), ''), 14)) = 'CREATE TRIGGER'
END
insert into @script select '----------------------------------------------';
insert into @script select '-- Creation of Triggers';
insert into @script select '';
insert into @script select '';
DECLARE ms_users CURSOR LOCAL forward_only FOR
SELECT
T.username,
T.objid,
MAX(D.lineid)
FROM
@Triggers T,
@TrigText D
WHERE
T.objid = D.objid
GROUP BY
T.username,
T.objid
FOR READ ONLY;
OPEN ms_users;
FETCH NEXT FROM ms_users INTO @UserName, @ObjID, @MaxID;
WHILE @@fetch_status = 0
BEGIN
insert into @script select 'setuser N''' + @UserName + '''' + CHAR(13) + CHAR(10);
insert into @script
SELECT
'-- Text of the Trigger' =
CASE lineid
WHEN 1 THEN 'GO' + CHAR(13) + CHAR(10) + linetext
WHEN @MaxID THEN linetext + 'GO'
ELSE linetext
END
FROM
@TrigText
WHERE
objid = @ObjID
ORDER
BY lineid;
insert into @script select 'setuser';
FETCH NEXT FROM ms_users INTO @UserName, @ObjID, @MaxID;
END;
CLOSE ms_users;
insert into @script select 'GO';
insert into @script select '------End ------';
DEALLOCATE ms_crs_syscom;
DEALLOCATE ms_users;
select script from @script order by id
END
How to execute it:
SET nocount ON
DECLARE @return_value INT
EXEC @return_value = [dbo].[SYS_ScriptAllTriggers] @InclDrop = 1
SELECT 'Return Value' = @return_value
GO
A: How about this?
select text from syscomments where text like '%CREATE TRIGGER%'
EDIT - per jj's comment below, syscomments is deprecated and will be removed in the future. Please use either the wizard-based or script-based solutions listed above moving forward :)
A: Database-> Tasks-> Generate Scripts -> Next -> Next
On Choose Script Options UI, under Table/View Options Heading, set Script Triggers to True.
A: Using my own version with the combination of answer found in here and other post(can't find the original quetion.
select OBJECT_NAME(parent_obj) AS table_name,sysobj.name AS trigger_name,
[definition],'GO'
from sys.sql_modules m
inner join sysobjects sysobj on sysobj.id=m.object_id
INNER JOIN sys.tables t ON sysobj.parent_obj = t.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE sysobj.type = 'TR' and sysobj.name like 'NAME_OF_TRIGGER'
order by sysobj.name | unknown | |
d16170 | val | The function that you provide for your view model (or as the createViewModel factory) will receive all of the params. For example:
define(['knockout', 'text!./my-tagname.html'], function(ko, templateString) {
function MyTagNameComponent(params) {
// do something with params here
}
return { viewModel: MyTagNameComponent, template: templateString };
});
So, your component will receive its params as the first argument to MyTagNameComponent in this case.
Here is a sample: http://jsfiddle.net/rniemeyer/g7zhjfz1/ | unknown | |
d16171 | val | It is the Xterm control sequence for iconify window.
An excerpt:
CSI Ps ; Ps ; Ps t
Window manipulation (from dtterm, as well as extensions).
These controls may be disabled using the allowWindowOps
resource. Valid values for the first (and any additional
parameters) are:
Ps = 1 -> De-iconify window.
Ps = 2 -> Iconify window.
Ps = 3 ; x ; y -> Move window to [x, y].
[...]
CSI is the control sequence initiator (ESC [). t is the "command", which allows for several types of window manipulation, the exact manipulation determined by parameters (indicated by Ps) that precede the t. The parameter 2 indicates the window should be iconified, which on Mac OS means to send it to the doc. | unknown | |
d16172 | val | how about this
setTimeout(function(){ /*your function*/ }, 3000);
https://www.w3schools.com/JSREF/met_win_setTimeout.asp | unknown | |
d16173 | val | You can start pretty easily using Flash Develop from: http://www.flashdevelop.org/
With Flash Develop, you can also start with an 'engine' or framework to make coding the game easier like FlashPunk (http://useflashpunk.net/) or Flixel (http://flixel.org/) | unknown | |
d16174 | val | assertEqual calls the appropriate type equality function (if available). e.g. assertEqual on lists actually calls assertListEqual. If no type equality function is specified, assertEqual simply uses the == operator to determine equality.
Note that you can make and register your own type equality functions if you wish.
If you want to look at the actual implementation, assertListEqual simply delegates to assertSequenceEqual which ultimately uses != to compare items. If the sub-items are nested, it gets compared however python compares those items. For example, lists are considered equal if:
Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.)
See the docs on python sequences. | unknown | |
d16175 | val | Per their documentation, https://stripe.com/docs/api they have 2 different APIs. You're trying to use the RESTful API, which is for retrieving information on demand.
They also have a WebHooks API, which requires you have an endpoint listening on your site which can accept event notifications. You configure these through your Dashboard with them.
The event type you're looking for specifically is probably the customer.subscription.deleted event, but there's a lot more you can do with them and I'd encourage you to explore all of those Webhooks.
I can't offer a code sample, as I don't use their service.
A: The strip.net example shows the subscriptionService.Cancel as a methed:
var subscriptionService = new StripeSubscriptionService();
subscriptionService.Cancel(*customerId*, *subscriptionId*);
But you can also use it as a function and it returns the subscription object.
var subscriptionService = new StripeSubscriptionService();
StripeSubscription stripeSubscription = subscriptionService.Cancel(*customerId*, *subscriptionId*);
If (stripeSubscription.Status != "canceled")
{
//subscription not cancelled
// take action
}
Per Stripe API docs:
Returns:
The canceled subscription object. Its subscription status will be set to "canceled" unless you've set at_period_end to true when canceling, in which case the status will remain "active" but the cancel_at_period_end attribute will change to true.One of the fiels is .status , witch is set to canceled. | unknown | |
d16176 | val | In your API request, try prefacing the tabLabel with \\*. For example, if multiple text tabs have the label "address", the portion of the API request to populate those tabs (each with the value '123 Main Street') would look like this:
"tabs":{
"textTabs":[
{
"tabLabel":"\\*address",
"value":"123 Main Street"
},
],
} | unknown | |
d16177 | val | The useEffect hook is not expected to fire on orientation change. It defines a callback that will fire when the component re-renders. The question then is how to trigger a re-render when the screen orientation changes. A re-render occurs when there are changes to a components props or state.
Lets make use of another related stackoverflow answer to build a useWindowDimensions hook. This allows us to hook into the windows size as component state so any changes will cause a re-render.
useWindowDimensions.js
import { useState, useEffect } from 'react';
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}
You can then use that hook in your component. Something like:
BikeImage.js
import React from 'react'
import useWindowDimensions from './useWindowDimensions'
export default () => {
const windowDimensions = useWindowDimensions();
// Define these helper functions as you like
const width = getImageWidth(windowDimensions.width)
const height = getImageHeight(windowDimensions.height)
// AppImage is a component defined elsewhere which takes
// at least width, height and src props
return <AppImage width={width} height={height} src="..." .../>
}
A: Here is a custom hook that fires on orientation change,
import React, {useState, useEffect} from 'react';
// Example usage
export default () => {
const orientation = useScreenOrientation();
return <p>{orientation}</p>;
}
function useScreenOrientation() {
const [orientation, setOrientation] = useState(window.screen.orientation.type);
useEffect(() => {
const handleOrientationChange= () => setOrientation(window.screen.orientation.type);
window.addEventListener('orientationchange', handleOrientationChange);
return () => window.removeEventListener('orientationchange', handleOrientationChange);
}, []);
return orientation;
}
Hope this takes you to the right direction.
A: You need to trigger a re-render, which can be done by setting state inside of your bikeImageHeight.
const [viewSize, setViewSize] = useState(0)
const bikeImageHeight = () => {
const windowViewportHeight = window.innerHeight;
const isLandscape = window.orientation === 90 || window.orientation === -90;
let bikeImgHeight = 0;
if (windowViewportHeight <= 450 && isLandscape) {
bikeImgHeight = windowViewportHeight - 50;
}
setViewSize(bikeImgHeight)
return bikeImgHeight;
};
And per the comments conversation, here's how you'd use debounce:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
const YourComponent = () => {
const bikeImageHeight = () => {
const windowViewportHeight = window.innerHeight;
const isLandscape = window.orientation === 90 || window.orientation === -90;
let bikeImgHeight = 0;
if (windowViewportHeight <= 450 && isLandscape) {
bikeImgHeight = windowViewportHeight - 50;
}
setViewSize(bikeImgHeight)
return bikeImgHeight;
};
const debouncedBikeHeight = debounce(bikeImageHeight, 200)
useEffect(() => {
bikeImageHeight();
window.addEventListener("resize", debouncedBikeHeight);
return () => {
window.removeEventListener("resize", debouncedBikeHeight);
};
}, []);
return <div>some jsx</div>
}
Example debounce taken from here: https://davidwalsh.name/javascript-debounce-function | unknown | |
d16178 | val | Is this really what you're aiming to do?
foreach($img->find('img') as $element)
$img[] = $element->src . '<br>';
$img is an object on the first foreach -loop, but then you're trying to access $img as an array, which is causing the error. Are you accidentally using the same variable name for two different things?
A: You have to put str_get_html before str_replace as:
$img_html = str_get_html('hhtml tekst html tekst <img src = "img.png" /> ad sad');
foreach($img_html->find('img') as $element)
$img[] = $element->src;
$img_html = str_get_html(str_replace($img[0], 'n-'.$img[0], $img_html));
foreach($img_html->find('img') as $element2)
echo $element2->src . '<br>';
Also check that you have given correct path in require_once( 'simple_html_dom.php'); | unknown | |
d16179 | val | You can extract gs value using following regular expression: gs=\"([^"]+)\". Always remember to escape " with \ in regular epressions, unless you want " to be evaluated as part of regular expression. | unknown | |
d16180 | val | Multiple solutions are possible:
*
*Start the DataStage job from command line (via dsjob) and schedule this job in the same scheduler (as the SQL server job) after that job (or schedule both in another common scheduler)
*Use a wait for file stage in the DataStage Sequence. This could be configured to wait some time for the file.
*Trigger the execution from a database trigger - I have done it for Db2 but it should be possible for you as well - maybe you have to write some code for that... | unknown | |
d16181 | val | Update!
http://jsfiddle.net/lsubirana/7od3sfrr/1/
HTML:
<div id="slider"></div>
<div class="left"><h3>My font color must change depending on slider-ui threshold</h3></div>
<div class="right"><h3>My font color must change depending on slider-ui threshold</h3></div>
CSS:
.left, .right {position:absolute; top: 0; left: 0; height: 100vh;overflow:hidden;}
.left h3 {color: white; text-align: center; margin-top: 30px;width:100vw;}
.right h3 {color: black; text-align: center; margin-top: 30px;width:100vw;}
Original Answer:
One method to obtain what you are looking for is to pass the slider percentage to a function that can return you an rgb color value. The following page shows how to create rainbows in javascript and I believe can be applied in this case:
http://krazydad.com/tutorials/makecolors.php
$(document).ready(function() {
$( "#slider" ).slider({
max: 101,
min:1,
value: 51,
slide: function(event,ui) {
var percentage = (ui.value)-1;
$('.left').css("width",percentage +'%');
$('h3').css('color', rgb(percentage));
}
});
});
function rgb(p){
var frequency = .08;
r = Math.sin(frequency*p + 0) * 127 + 128;
g = Math.sin(frequency*p + 2) * 127 + 128;
b = Math.sin(frequency*p + 4) * 127 + 128;
return 'rgb(' + Math.round(r) + ',' + Math.round(g) + ',' + Math.round(b) + ')';
}
http://jsfiddle.net/lsubirana/376ow969/ | unknown | |
d16182 | val | Just press ALT + CMD + I and the Dev.Tools will open.
With SHIFT + CMD + M you switch to the device-emulator.
At "Screen" fill in your resolution. Reload the page for best results. | unknown | |
d16183 | val | Two points:
1) Is MouseDown="Window_MouseUp" everywhere intended?
2) Why not register to Click event with ClickMode="Press" instead of MouseDown. I don't think Button provides/raises MouseDown unless may be with a custom template.
Example:
<Button Grid.Row="3"
Margin="5"
Name="cmd_Clear"
ClickMode="Press"
Click="Cmd_Clear_MouseDown">Clear</Button> | unknown | |
d16184 | val | You should check the difference between:
*
*global, class and instance variables
*class and instance methods
Your are close to a working exemple with an instance variable:
class Dictionary
def initialize
@dictionary_hash = {"Apple"=>"Apples are tasty"}
end
def new_word
puts "Please type a word and press enter"
new_word = gets.chomp.upcase
puts "Thanks. You typed: #{new_word}"
@dictionary_hash[new_word] = "#{new_word} means something about something. More on this later."
finalize
new_word
end
def finalize
puts "To enter more, press Y then press Enter. Otherwise just press Enter."
user_choice = gets.chomp.upcase
if user_choice == "Y"
new_word
else
puts @dictionary_hash
end
end
end
d = Dictionary.new
d.new_word | unknown | |
d16185 | val | I was able to manually fix it using add_axes. (Thank goodness for colleagues!)
cbar_ax = fig.add_axes([0.09, 0.06, 0.84, 0.02])
fig.colorbar(thplot, cax=cbar_ax, orientation="horizontal")
A: Looking for the same answer I think I found something easier to work with compatible with the current version of Matplotlib to decrease the width of the colorbar. One can use the "ratio" option of the matplolib.figure function (see http://matplotlib.org/api/figure_api.html). And here is an example :
import numpy as np
from matplotlib import pyplot as plt
# generate data
x = np.random.normal(0.5, 0.1, 1000)
y = np.random.normal(0.1, 0.5, 1000)
hist = plt.hist2d(x,y, bins=100)
plt.colorbar(aspect=20)
plt.colorbar(aspect=50)
A: I was able to use a combination of fraction and aspect parameters to get the desired width of the colorbar while it still stretched across the plot. | unknown | |
d16186 | val | Well, youβre trying to instantiate and show with timer your own launch screen (not good!) while also asking iOS to do one. Just get rid of most or all of this code. Use the standard approach of having a launch storyboard then set up your main VC as normal in your appDelegate.
Using that timer is making assumptions about the timing of each app launch that iOS canβt guarantee. | unknown | |
d16187 | val | You're using multiple modules of Hibernate Search, but without different versions (5.7.0.Final and 5.6.1.Final). Use the same version for each Hibernate Search module, in your case 5.7.0.Final:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.7.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-elasticsearch</artifactId>
<version>5.7.0.Final</version>
</dependency> | unknown | |
d16188 | val | Personally, I tend to work as follows:
*
*Design the data warehouse first. In particular, design the tables that are needed as part of the DW, ignoring any staging tables.
*Design the ETL, using SSIS, but sometimes with SSIS calling stored procedures in the involved databases.
*If any staging tables are required as part of the ETL, fine, but at the same time make sure they get cleaned up. A staging table used only as part of a single series of ETL steps should be truncated after those steps are completed, with or without success.
*I have the SSIS packages refer to the OLTP database at least to pull data into the staging tables. Depending on the situation, they may process the OLTP tables directly into the data warehouse. All such queries are performed WITH(NOLOCK).
*Document, Document, Document. Make it clear what inputs are used by each package, and where the output goes. Make sure to document the criteria by which the input are selected (last 24 hours? since last success? new identity values? all rows?)
This has worked well for me, though I admit I haven't done many of these projects, nor any really large ones.
A: I'm currently working on a small/mid size dataware house. We're adopting some of the concepts that Kimball puts forward, i.e. the star scheme with fact and dimension tables. We structure it so that facts only join to dimensions (not fact to fact or dimension to dimension - but this is our choice, not saying it's the way it should be done), so we flatten all dimension joins to the fact table.
We use SSIS to move the data from the production DB -> source DB -> staging DB -> reporting DB (we probably could have have used less DBs, but that's the way it's fallen).
SSIS is really nice as it's lets you structure your data flows very logically. We use a combination of SSIS components and stored procs, where one nice feature of SSIS is the ability to provide SQL commands as a transform between a source/destination data-flow. This means we can call stored procs on every row if we want, which can be useful (albeit a bit slower).
We're also using a new SQL Server 2008 feature called change data capture (CDC) which allows you to audit all changes on a table (you can specify which columns you want to look at in those tables), so we use that on the production DB to tell what has changed so we can move just those records across to the source DB for processing.
A: I agree with the highly rated answer but thought I'd add the following:
* Do you use a staging area to perform the transformation and then
load into the warehouse?
It depends on the type of transformation whether it will require staging. Staging offers benefits of breaking the ETL into more manageable chunks, but also provides a working area that allows manipulations to take place on the data without affecting the warehouse. It can help to have (at least) some dimension lookups in a staging area which store the keys from the OLTP system and the key of the latest dim record, to use as a lookup when loading your fact records.
The transformation happens in the ETL process itself, but it may or may not require some staging to help it along the way.
* How do you link data between the warehouse and the OLTP database?
It is useful to load the business keys (or actual primary keys if available) into the data warehouse as a reference back to the OLTP system. Also, auditing in the DW process should record the lineage of each bit of data by recording the load process that has loaded it.
* Where/How do you manage the transformation process - in the
database as sprocs, dts/ssis packages,
or SQL from application code?
This would typically be in SSIS packages, but often it is more performant to transform in the source query. Unfortunately this makes the source query quite complicated to understand and therefore maintain, so if performance is not an issue then transforming in the SSIS code is best. When you do this, this is another reason for having a staging area as then you can make more joins in the source query between different tables.
A: John Saunders' process explanation is a good.
If you are looking to implement a Datawarehouse project in SQL Server you will find all the information you require for the delivering the entire project within the excellent text "The Microsoft Data Warehouse Toolkit".
Funilly enough, one of the authors is Ralph Kimball :-)
A: You may want to take a look at Data Vault Modeling. It claims solving some loner term issues like changing attributes. | unknown | |
d16189 | val | Empty deques are falsey, non-empty deques are truthy:
>>> bool(deque([]))
False
>>> bool(deque([1, 2]))
True
This will not iterate through each deque:
non_empty_dqs = {k: v for k, v in dqs.items() if v} | unknown | |
d16190 | val | You can easy learn i have searched it
*
*It's a great and simple tutorial which help you step by step(After covering this tutorial you will be able to handle admin panel of the magento)
http://www.templatemonster.com/help/ecommerce/magento/magento-tutorials/
http://leveluptuts.com/tutorials/magento-community-tutorials | unknown | |
d16191 | val | The problem is that when you use ko-mapping, it turns every property into an observable. The new genres you create are not the same kind of object as the initial objects, because they are just standard vanilla objects. So the genre you are trying to remove from the track is not the same one you removed from the album.
A simple way to fix your issue is to alter the remove function, as in this fiddle.
$.each(this.tracks(), function(index, track) {
var toRemove = ko.utils.arrayFirst(track.genres(), function(item) {
return ko.utils.unwrapObservable(genre.id) == ko.utils.unwrapObservable(item.id);
});
track.genres.remove(toRemove);
});
A better way would be to be a little more thorough in generating your initial viewmodel, the new genres, or both. This won't be easy. | unknown | |
d16192 | val | Assume the grouping order is not important, you can just group inside a DoFn.
class Group(beam.DoFn):
def __init__(self, n):
self._n = n
self._buffer = []
def process(self, element):
self._buffer.append(element)
if len(self._buffer) == self._n:
yield list(self._buffer)
self._buffer = []
def finish_bundle(self):
if len(self._buffer) != 0:
yield list(self._buffer)
self._buffer = []
lines = p | 'File reading' >> ReadFromText(known_args.input)
| 'Group' >> beam.ParDo(Group(known_args.N)
... | unknown | |
d16193 | val | I actually implemented this requirement with the help of a launcher. The below were the settings that I have done. Its activates only those pages which are modified under the mentioned path.
A: *
*You can define the workflow launcher to listen to a specific property. So if your nightly update updates a specific property, the easiest is to have a launcher that checks for modification of this property:
http://docs.adobe.com/docs/en/cq/current/workflows/wf-using.html#Starting Workflows When Nodes Change
*Usually you should only log in as admin if you need to access system settings (/system/console) and not for daily work. I suggest you create an administrator user which is part of the group that would get the workflow notification. You can give this user full access to the CRX, but still I would really check if this is needed for daily tasks.
A: Depending on your concrete requirements, if you want to activate the pages without starting a workflow first you can make use of the com.day.cq.replication package. If you obtain a reference to a Replicator object you can trigger replication of a node simply via a call to the replicate method. | unknown | |
d16194 | val | Many of blenders operators require a certain context to be right before they will work, for bpy.ops.image.save() that includes the UV/Image editor having an active image. While there are ways to override the current context to make them work, it can often be easier to use other methods.
The Image object can save() itself. If it is a new image you will first need to set it's filepath, you may also want to set it's file_format.
img = bpy.data.images['imagename']
img.filepath = '/path/to/save/imagename.png'
img.file_format = 'PNG'
img.save() | unknown | |
d16195 | val | To enable multi-domain, you need to check 3 things
*
*Each origin has a .well-known/assetlinks.json file
*The android asset_statements contains all origins
*Tell the Trusted Web Activity about additional origins when launching.
It seems you have the first two points covered, but not the last one.
Using the support library LauncherActivity:
If using the LauncherActivity that comes with the library, you can provide additional origins by updating the AndroidManifest:
*
*Add a list of additional origins to res/values/strings.xml:
<string-array name="additional_trusted_origins">
<item>https://www.google.com</item>
</string-array>
*Update AndroidManifest.xml:
<activity android:name="com.google.androidbrowserhelper.trusted.LauncherActivity"
android:label="@string/app_name">
<meta-data
android:name="android.support.customtabs.trusted.ADDITIONAL_TRUSTED_ORIGINS"
android:resource="@array/additional_trusted_origins" />
...
</activity>
Using a custom LauncherActivity
If using your own LauncherActivity, launching with additional origins can implemented like this:
public void launcherWithMultipleOrigins(View view) {
List<String> origins = Arrays.asList(
"https://checkout.example.com/"
);
TrustedWebActivityIntentBuilder builder = new TrustedWebActivityIntentBuilder(LAUNCH_URI)
.setAdditionalTrustedOrigins(origins);
new TwaLauncher(this).launch(builder, null, null);
}
Resources:
*
*Article with more details here: https://developers.google.com/web/android/trusted-web-activity/multi-origin
*Sample multi-origin implementation: https://github.com/GoogleChrome/android-browser-helper/tree/master/demos/twa-multi-domain | unknown | |
d16196 | val | The first parameter of the Animation constructor is the frameDuration in seconds. You are passing it 1/15f, which is really fast. Try something greater, like 0.15f. | unknown | |
d16197 | val | Those two SOAP bodies are exactly the same.
A namespace prefix in an element tag is just a symbolic shorthand for a namespace URI.
An XML document can define a namespace prefix using an attribute that starts with xmlns::
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
That attribute means βall names in this element and its descendants starting with soapenv: are actually names associated with the URI http://schemas.xmlsoap.org/soap/envelope/.β
The following namespace definition is exactly the same thing; it just specifies a different prefix to use as shorthand for the same URI:
xmlns:x="http://schemas.xmlsoap.org/soap/envelope/"
So, the only difference is that the two XML documents is how they refer to the βhttp://schemas.xmlsoap.org/soap/envelope/β URI:
*
*The first document specifies that elements starting with soapenv: are associated with that URI.
*The second document specifies that elements starting with x: are associated with that URI.
The notation is different, but the meaning is the same. They literally have identical content. | unknown | |
d16198 | val | I'm guessing the binding redirect isn't set up correctly in the web.config file. Try running this in the nuget package manager console:
PM> Get-Project βAll | Add-BindingRedirect
A: This ended up being a bit of a misunderstanding on my part from following the Umbraco videos. I was attempting to set up a new Visual Studio project, import all the DLLs needed, and then move the site content into the project.
All I really needed to do was create a blank project, then move the site content, with all of its DLLs, into the project. This let me immediately start editing the project.
A: The best solution was to install an earlier version of the package and then upgrade. | unknown | |
d16199 | val | It's because of the way that the language is parsed.
decltype(obj)::iterator it = obj.begin();
You want it to become
(decltype(obj)::iterator) it;
But in actual fact, it becomes
decltype(obj) (::iterator) it;
I have to admit, I was also surprised to see that this was the case, as I'm certain that I've done this before. However, in this case, you could just use auto, or even decltype(obj.begin()), but in addition, you can do
typedef decltype(obj) objtype;
objtype::iterator it;
A: Yet another workaround until VC++'s parser is fixed to reflect the FDIS is to use the std::identity<> metafunction:
std::identity<decltype(obj)>::type::iterator it = obj.begin();
A: Your code is well-formed according to the final C++0x draft (FDIS). This was a late change that's not yet been implemented by the Visual Studio compiler.
In the meantime, a workaround is to use a typedef:
typedef decltype(obj) obj_type;
obj_type::iterator it = obj.begin();
EDIT: The relevant chapter and verse is 5.1.1/8:
qualified-id:
[...]
nested-name-specifier templateopt unqualified-id
nested-name-specifier:
[...]
decltype-specifier ::
decltype-specifier:
decltype ( expression )
And for completeness's sake:
The original core issue
Proposal for wording | unknown | |
d16200 | val | You can cause the "moon" to revolve around a point by animating it along a bezier path, and at the same time animate a rotation transform. Here is a simple example,
@interface ViewController ()
@property (strong,nonatomic) UIButton *moon;
@property (strong,nonatomic) UIBezierPath *circlePath;
@end
@implementation ViewController
-(void)viewDidLoad {
self.moon = [UIButton buttonWithType:UIButtonTypeInfoDark];
[self.moon addTarget:self action:@selector(clickedCircleButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.moon];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
CGRect circleRect = CGRectMake(60,100,200,200);
self.circlePath = [UIBezierPath bezierPathWithOvalInRect:circleRect];
self.moon.center = CGPointMake(circleRect.origin.x + circleRect.size.width, circleRect.origin.y + circleRect.size.height/2.0);
}
- (void)clickedCircleButton:(UIButton *)sender {
CAKeyframeAnimation *orbit = [CAKeyframeAnimation animationWithKeyPath:@"position"];
orbit.path = self.circlePath.CGPath;
orbit.calculationMode = kCAAnimationPaced;
orbit.duration = 4.0;
orbit.repeatCount = CGFLOAT_MAX;
[self.moon.layer addAnimation:orbit forKey:@"circleAnimation"];
CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
fullRotation.fromValue = 0;
fullRotation.byValue = @(2.0*M_PI);
fullRotation.duration = 4.0;
fullRotation.repeatCount = CGFLOAT_MAX;
[self.moon.layer addAnimation:fullRotation forKey:@"Rotate"];
}
These particular values will cause the "moon" to keep the same face toward the center like earth's moon does.
A: Use two layers.
*
*One is an invisible "arm" reaching from the earth to the moon. It does a rotation transform around its anchor point, which is the center of the earth. This causes the moon, out at the end of the "arm", to revolve around the earth.
*The other is the moon. It is a sublayer of the "arm", sitting out at the end of the arm. If you want it to rotate independently, rotate it round its anchor point, which is its own center.
(Be aware, however, that the real moon does not do this. For the real moon, the "arm" is sufficient, because the real moon rotates in sync with its own revolution around the earth - so that we see always the same face of the moon.)
A: I was looking for this kind of implementation myself.
I followed rdelmar answer and used this swift version:
class ViewController: UIViewController {
var circlePath: UIBezierPath!
var moon = UIButton(frame: CGRect(x: 10, y: 10, width: 50, height: 50))
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
let circleRect = CGRect(x: 60, y: 100, width: 200, height: 200)
self.circlePath = UIBezierPath(ovalIn: circleRect)
self.moon.center = CGPoint(x: circleRect.origin.x + circleRect.size.width, y: circleRect.origin.y + circleRect.size.height/2.0)
self.moon.addTarget(self, action: #selector(didTap), for: .touchUpInside)
moon.backgroundColor = .blue
self.view.addSubview(moon)
}
@objc func didTap() {
let orbit = CAKeyframeAnimation(keyPath: "position")
orbit.path = self.circlePath.cgPath
orbit.calculationMode = .paced
orbit.duration = 4.0
orbit.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
moon.layer.add(orbit, forKey: "circleAnimation")
let fullRotation = CABasicAnimation(keyPath: "transform.rotation.z")
fullRotation.fromValue = 0
fullRotation.byValue = CGFloat.pi*2
fullRotation.duration = 4
fullRotation.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
moon.layer.add(orbit, forKey: "Rotate")
}
} | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.