id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23530900
|
$xml = [xml]''
$xml.Load("C:\New folder\untrimmed.xml")
$node = $xml.SelectSingleNode("//record[@category='COMPANY']")
while ($node -ne $null) {
$node.ParentNode.RemoveChild($node)
$node = $xml.SelectSingleNode("//record[@category='COMPANY']")
$xml.save("C:\New folder\trimmed.xml")
After this is completed after an hour and a half, the trimmed down file is BIGGER in size than the original. How can I do this in a better way? Is powershell not the right tool for the job here?
A: Try the new Gizmo tool in Saxon 10.0.
java net.sf.saxon.Gizmo -s:"C:\New folder\untrimmed.xml"
/>delete //record[@category='COMPANY']
/>save C:\New folder\untrimmed.xml
/>quit
Caveat: I haven't tried it with filenames containing spaces.
Gizmo doesn't currently use streaming, unfortunately (we had a prototype that does, but it's not released), so you'll need a fair bit of memory for this to run.
If streaming is essential, you can do it with a streaming XSLT 3.0 stylesheet:
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0">
<xsl:mode streamable="yes" on-no-match="shallow-copy"/>
<xsl:template match="record[@category='COMPANY']"/>
</xsl:transform>
| |
doc_23530901
|
enter code hereException in thread "main" java.util.zip.ZipException: zip file is empty
at java.base/java.util.zip.ZipFile$Source.zerror(ZipFile.java:1567)
at java.base/java.util.zip.ZipFile$Source.findEND(ZipFile.java:1375)
at java.base/java.util.zip.ZipFile$Source.initCEN(ZipFile.java:1469)
at java.base/java.util.zip.ZipFile$Source.<init>(ZipFile.java:1274)
at java.base/java.util.zip.ZipFile$Source.get(ZipFile.java:1237)
at java.base/java.util.zip.ZipFile$CleanableResource.<init>(ZipFile.java:727)
at java.base/java.util.zip.ZipFile$CleanableResource.get(ZipFile.java:844)
at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:247)
at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:177)
at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:191)
at org.gradle.wrapper.Install.unzip(Install.java:214)
at org.gradle.wrapper.Install.access$600(Install.java:27)
at org.gradle.wrapper.Install$1.call(Install.java:74)
at org.gradle.wrapper.Install$1.call(Install.java:48)
at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
at org.gradle.wrapper.Install.createDist(Install.java:48)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Complete error on machine
A: Browse to the official Gradle Distributions webpage and check what is the latest version of gradle all.zip file, for example (at the time of writing) gradle-6.7-all.zip and copy the address
Go to your Flutter project dropdown,
drop down android>gradle>wrapper
Select gradle-wrapper-properties
Paste the URL you copied earlier. For example:
distributionUrl=https://services.gradle.org/distributions/gradle-6.7-all.zip
A: solved it last,the issue was with permissions had to change owner of both the flutter and project folder.
| |
doc_23530902
|
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({ /*...*/ });
var params = {
//...
"body" : {
"template":"*",
"settings":{
"index.mapper.dynamic":true
//...
},
"mappings":{
"_default_":{
"properties":{
//...
},
"dynamic_templates":[{
"template_purchases_inner_fields": {
"path_match":"purchases.*",
"mapping": { "include_in_all": false }
}
}
//, ...
]
}
}
}
};
client.indices.putTemplate(params,function(err,resp){})
However, the Index templates docs say
Templates are only applied at index creation time. Changing a template will have no impact on existing indices
The Dynamic templates docs say
New templates can be appended to the end of the list with the PUT mapping API
The PUT mapping API has some examples, none of which fit to my scenario. An answer using indices.putMapping() would be extra helpful, but not necessary. Thanks for your time!
[Edited on 8-21-2017, Solar Eclipse day]
This is the code I tried to change it through the JS API:
var dynamicTemplates = [{
"template_purchases_inner_fields": {
"path_match": "purchases.*",
"mapping": { "include_in_all": false}
}
}
//...
];
params = { body: { "dynamic_templates": dynamicTemplates }};
params.index = "_all";
params.type = "_default_";
//...
client.indices.putMapping(params,function(err,resp){})
And this is the code through Linux curl, w/ the properties field removed. Please notice that you should re-add here other templates not to override the previous ones:
curl -XPUT http://localhost:9200/_all/_default_/_mapping -d "{\"_default_\":{\"dynamic_templates\":[{\"template_purchases_inner_fields\":{\"mapping\":{\"include_in_all\":false},\"path_match\":\"purchases.*\"}}]}}"
Checking on elasticsearch-head, on both cases, the mapping was updated on existing indices too, as if it worked. However, the include_in_all=false behavior was not achieved, meaning we could still see results on searching _all on records containing the inner objects under purchases.* on existing indices.
Related items:
*
*Create or update mapping in elasticsearch
*ElasticSearch client.indices.putMapping always fail
*PutMapping api url is incorrect
A: The current answer is we cannot apply it to an existing index, based on the Index templates docs:
Templates are only applied at index creation time. Changing a template will have no impact on existing indices
| |
doc_23530903
|
I have an abstract Pet class and have subclasses Dog and Bird which extend from the Pet parent class.
public abstract class Pet {
private String name;
private int age;
private String color;
public Pet(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
public void speak() {
System.out.println("I am a speak method of main class");
}
}
public class Dog extends Pet{
private String numberOfTeeth;
public Dog(String name, int age, String color, String numberOfTeeth) {
super(name, age, color);
this.numberOfTeeth = numberOfTeeth;
}
public String getNumberOfTeeth() {
return numberOfTeeth;
}
public void setNumberOfTeeth(String numberOfTeeth) {
this.numberOfTeeth = numberOfTeeth;
}
public void playFetch() {
System.out.println("dog is playing fetch");
}
}
public class Bird extends Pet{
private int flapsPerSecond;
public Bird(String name, int age, String color, int flapsPerSecond) {
super(name, age, color);
this.flapsPerSecond = flapsPerSecond;
}
public void fly() {
System.out.println("the bird is flying");
}
}
Now I am trying to create a database for the pets objects. The dilemma is that I am not sure if I should create separate tables for the Dog and Bird class or should just have the one single Pet table. In the front end, I am trying to implement functions specific to the type of pet. For example, if the object type is Dog, then create a button that makes a barking sound. And if the object type is Bird, then create a button that makes birds' wings flapping noise. I was thinking of creating a column called 'Species' on the Pet Table and it state whether the Pet is a Dog or a Bird. And when we pull the data from the database, if we see that Species string value is Dog, then create appropriate buttons accordingly.
A: There are multiple strategies to store polymorphism classes in the database.
Take a look at the Hibernate-ORM docs section 2.11 Inheritence. Those 5 subsections are basically 5 different strategies. Each has trade-offs on query efficiency, data size, etc.
For example, you can put Bird and Dog and Pet:
*
*or in a single table (Pet). This means that the column Pet.flapsPerSecond is null for a dog
*or in 3 different tables (Pet, Bird, Dog). This means that loading a dog requires querying both Dog and Pet.
*or in 2 tables (Bird, Dog). This mean to query all pets, you need to union results after running the queries.
*...
The examples here are just the tip of the icebergs of the trade-offs.
| |
doc_23530904
|
I am trying to understand the benefit of the error correcting version. Wouldn't the simpler version be less prone to errors since the individual blocks are larger? Also, doesn't the error correction defeat its own purpose by necessitating a more complex code which could become more easily corrupted?
Which would you recommend? The QR will appear physically and could wear over time.
A: Do your application need a QR Code instead of a regular barcode ? Most application such as ZXING is capable to scan QR or 1D barcode.
Error correction is highly useful it the print quality is poor or if the code is exposed to external elements(thus deteriorating the code) such as on a e packaging of frozen meat or on printed advertisement enclosed behind glass. In such cases a portion of the code may be unreadable, error correction will "recover" these portion. Sometime designer will deliberate "corrupt" the code to make it aesthetically pleasing and the error correction will be used for sure.
My opinion is , if space allows add in the error correction mechanism .
| |
doc_23530905
|
I've also, thanks to another question on here, got a function that will solve a quadratic equation.
The only problem now is that the code generates a parsing error in hugs, when trying to solve a quadratic with complex roots.
i.e. In hugs...
Main> solve (Q 1 2 1)
(-1.0,-1.0)
Main> solve (Q 1 2 0)
(0.0,-2.0)
Main> solve (Q 1 2 2)
(
Program error: pattern match failure: v1618_v1655 (C -1.#IND -1.#IND)
It looks to my like its a problem after the square-root has been applied, but I'm really not sure. Any help trying to pick up what is going wrong or any indications as to what this error means would be brilliant.
Thanks,
Thomas
The Code:
-- A complex number z = (re +im.i) is represented as a pair of Floats
data Complex = C {
re :: Float,
im :: Float
} deriving Eq
-- Display complex numbers in the normal way
instance Show Complex where
show (C r i)
| i == 0 = show r
| r == 0 = show i++"i"
| r < 0 && i < 0 = show r ++ " - "++ show (C 0 (i*(-1)))
| r < 0 && i > 0 = show r ++ " + "++ show (C 0 i)
| r > 0 && i < 0 = show r ++ " - "++ show (C 0 (i*(-1)))
| r > 0 && i > 0 = show r ++ " + "++ show (C 0 i)
-- Define algebraic operations on complex numbers
instance Num Complex where
fromInteger n = C (fromInteger n) 0 -- tech reasons
(C a b) + (C x y) = C (a+x) (b+y)
(C a b) * (C x y) = C (a*x - b*y) (b*x + b*y)
negate (C a b) = C (-a) (-b)
instance Fractional Complex where
fromRational r = C (fromRational r) 0 -- tech reasons
recip (C a b) = C (a/((a^2)+(b^2))) (b/((a^2)+(b^2)))
root :: Complex -> Complex
root (C x y)
| y == 0 && x == 0 = C 0 0
| y == 0 && x > 0 = C (sqrt ( ( x + sqrt ( (x^2) + 0 ) ) / 2 ) ) 0
| otherwise = C (sqrt ( ( x + sqrt ( (x^2) + (y^2) ) ) / 2 ) ) ((y/(2*(sqrt ( ( x + sqrt ( (x^2) + (y^2) ) ) / 2 ) ) ) ) )
-- quadratic polynomial : a.x^2 + b.x + c
data Quad = Q {
aCoeff, bCoeff, cCoeff :: Complex
} deriving Eq
instance Show Quad where
show (Q a b c) = show a ++ "x^2 + " ++ show b ++ "x + " ++ show c
solve :: Quad -> (Complex, Complex)
solve (Q a b c) = ( sol (+), sol (-) )
where sol op = (op (negate b) $ root $ b*b - 4*a*c) / (2 * a)
A: Your numbers seem denormalized in your error :
(C -1.#IND -1.#IND)
In this case, you can't assume that any comparison on float are valid anymore. This is in the definition of floating point numbers. Then your definition of show
show (C r i)
| i == 0 = show r
| r == 0 = show i++"i"
| r < 0 && i < 0 = show r ++ " - "++ show (C 0 (i*(-1)))
| r < 0 && i > 0 = show r ++ " + "++ show (C 0 i)
| r > 0 && i < 0 = show r ++ " - "++ show (C 0 (i*(-1)))
| r > 0 && i > 0 = show r ++ " + "++ show (C 0 i)
leave opportunity for a pattern failure, because of denormalized numbers. You can add the following condition
| otherwise = show r ++ "i" ++ show i"
Now for the why is it like that, when you evaluate
b * b - 4 * a * c
with Q 1 2 2, you obtain -4, and then in root, you fall in your last case, and in the second equation :
y
-----------------------------
________________
/ _______
/ / 2 2
/ x + \/ x + y
2 * \ / ----------------
\/ 2
-4 + sqrt( (-4) ^2) == 0, from there, you're doomed, division by 0, followed by a "NaN" (not a number), screwing everything else
A: Dave hit the nail on the head.
With the original code in GHCi, I get:
*Main> solve (Q 1 2 2)
(*** Exception: c.hs:(11,4)-(17,63): Non-exhaustive patterns in function show
If we update the show block:
instance Show Complex where
show (C r i)
| i == 0 = show r
| r == 0 = show i++"i"
| r < 0 && i < 0 = show r ++ " - "++ show (C 0 (i*(-1)))
| r < 0 && i > 0 = show r ++ " + "++ show (C 0 i)
| r > 0 && i < 0 = show r ++ " - "++ show (C 0 (i*(-1)))
| r > 0 && i > 0 = show r ++ " + "++ show (C 0 i)
| otherwise = "???(" ++ show r ++ " " ++ show i ++ ")"
then we get this information in GHCi:
*Main> :l c.hs
[1 of 1] Compiling Main ( c.hs, interpreted )
c.hs:22:0:
Warning: No explicit method nor default method for `abs'
In the instance declaration for `Num Complex'
c.hs:22:0:
Warning: No explicit method nor default method for `signum'
In the instance declaration for `Num Complex'
Ok, modules loaded: Main.
*Main> solve (Q 1 2 2)
(???(NaN NaN),???(NaN NaN))
I was "born and raised" on GHCi, so I don't know exactly how Hugs compares in verbosity of warnings and errors; but it looks like GHCi is a clear winner in telling you what went wrong.
A: Off the top of my head: It could be a problem with your definition of show for Complex.
I notice you don't have default case like this:
| otherwise = ...
Therefore if your conditions with r and i are non exhaustive you'll get a pattern match failure.
| |
doc_23530906
|
I am facig some problem with c++ templates.
Here is what my class structure looks like.
class abstract_logger_t {
public:
typedef abstract_logger_t logger_type;
template<typename data_t>
abstract_logger_t& log(const data_t& data) {
return *this;
}
};
class stdout_logger_t : public abstract_logger_t {
public:
typedef stdout_logger_t logger_type;
template<typename data_t>
stdout_logger_t& log(const data_t& data) {
cout << data << endl;
return *this;
}
};
template<typename logger_t, typename data_t>
void output(logger_t& logger, const data_t& data) {
static_cast<typename logger_t::logger_type&>(logger).log(data);
cout << data;
}
template<typename data_t>
abstract_logger_t& operator<< (abstract_logger_t& logger, const data_t& data) {
output(logger, data);
return logger;
}
stdout_logger_t logger;
logger << "Hi " << 1;
Here I am expecting stdout_logger_t::log to be called by output.
but it looks like derived type is getting lost
and abstract_logger_t::log ends up getting called.
Can someone tell me if I am doing something wrong ?
A: There is no need to make things more complicated than they should be.
Heritage here is useless, unless you want to use virtual methods, in which case you won't make much use of templates.
Here is an updated version of your code. Simply add other logger classes when you need new ones.
class stdout_logger_t
{
public:
typedef stdout_logger_t logger_type;
template<typename data_t>
logger_type& log(const data_t& data) {
cout << data << endl;
return *this;
}
};
class lazy_logger_t
{
public:
typedef lazy_logger_t logger_type;
template<typename data_t>
logger_type& log(const data_t& data) {
return *this;
}
};
template<typename logger_t, typename data_t>
void output(logger_t& logger, const data_t& data) {
logger.log(data);
}
template<typename logger_t, typename data_t>
logger_t& operator<< (logger_t& logger, const data_t& data) {
output(logger, data);
return logger;
}
stdout_logger_t logger;
lazy_logger_t lazyLogger;
logger << "Hi " << 1;
lazyLogger << "Hi " << 1;
Be careful, i am pretty sure this logger system won't work with std::endl.
A: template<typename data_t>
abstract_logger_t& operator<< (abstract_logger_t& logger, const data_t& data) {
output(logger, data);
return logger;
}
Here, whatever logger you pass in, the compiler will convert it into an abstract_logger_t&. You need to make the first argument templated too.
template<typename T, typename data_t>
T& operator<< (T& logger, const data_t& data) {
output(logger, data);
return logger;
}
A: It seems you are confusing templates with runtime polymorphism. Also, your abstract_logger_t class is not abstract. You're invokung output from operator<< with logger_t=abstract_logger_t. The template parameter is determined via checking static types, not the dynamic types. Template argument deduction and template instantiation are compile-time mechanisms. This should answer your question.
BTW: The convention is to use CamlCase names for template parameters.
| |
doc_23530907
|
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
I am getting
Use of undeclared identifier 'AFNetworkActivityIndicatorManager'.
What's wrong?
| |
doc_23530908
|
bandClient.SensorManager.HeartRate.ReadingChanged += HeartRate_ReadingChanged;
Then I try to update the value like this:
private void HeartRate_ReadingChanged(object sender, Microsoft.Band.Sensors.BandSensorReadingEventArgs<Microsoft.Band.Sensors.IBandHeartRateReading> e)
{
HeartRate = e.SensorReading.HeartRate;
}
HeartRate is an int set like so:
public int HeartRate
{
get { return (int)GetValue(HeartRateProperty); }
set { SetValue(HeartRateProperty, value); }
}
// Using a DependencyProperty as the backing store for HeartRate. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HeartRateProperty =
DependencyProperty.Register("HeartRate", typeof(int), typeof(MainPage), new PropertyMetadata(0));
The TextBlock text is then bound to HeartRate. However, I keep getting this error when trying to set HeartRate:
The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
My guess is that it's trying to set HeartRate while it is still being set from the call before.
A: Try to implement this and see how it goes, if you still want your int variable, then convert it back to string when displaying it in a text-block.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
Textblock.Text = e.SensorReading.HeartRate.ToString())
}).AsTask();
| |
doc_23530909
|
Here are the instructions I used:
apt-get install perl6 && \
git clone https://github.com/ugexe/zef.git && cd zef && perl6 -I. bin/zef install . && \
/usr/lib/perl6/site/bin/zef install Shell::Command && \
PYTHON_CONFIG=/usr/bin/python3-config \
/usr/lib/perl6/site/bin/zef -v install https://github.com/eatingtomatoes/Inline-Python3.git --/test --debug
Following is the output:
....
===> Building [OK] for Inline::Python3:ver<0.1>
===> Installing: LibraryMake:ver<1.0.0>:auth<github:retupmoca>
===> Install [OK] for LibraryMake:ver<1.0.0>:auth<github:retupmoca>
===> Installing: Inline::Python3:ver<0.1>
===> Install [FAIL] for Inline::Python3:ver<0.1>: ===SORRY!===
Probable version skew in pre-compiled
'site#sources/95D204DDA68A3E05E891AA531EBED9270C46B3F7
(Inline::Python3::InstanceConverter)' (cause: no object at index 499)
===SORRY!===
Probable version skew in pre-compiled
'site#sources/95D204DDA68A3E05E891AA531EBED9270C46B3F7
(Inline::Python3::InstanceConverter)' (cause: no object at index 499)
When I executed perl6 -e "use Inline::Python3; say 'hi'" in shell, it reported:
===SORRY!===
Probable version skew in pre-compiled
'site#sources/95D204DDA68A3E05E891AA531EBED9270C46B3F7
(Inline::Python3::InstanceConverter)' (cause: no object at index 499)
The Inline::Python3 package is a perl6 package developped by myself. It runs well on my pc.
perl6 --version said:
This is Rakudo version 2018.03 built on MoarVM version 2018.03
implementing Perl 6.c.
I don't know what the 'version skew' is. How can I fix the error?
A: Following @jjmerelo's advice, using the latest compiler provided by rakudo-pkg solved the problem.
| |
doc_23530910
|
i want to store song name into database from sd card. i use the following code but it does not store song name. it store wrong content.
my code is :
final String[] proj = { MediaStore.Audio.Media._ID,MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.DISPLAY_NAME,MediaStore.Audio.Media.SIZE };
Log.e("media",""+proj.length);
SQLiteDatabase db;
db = openOrCreateDatabase("TestData.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
final String CREATE_TABLE_COUNTRIES ="CREATE TABLE IF NOT EXISTS songs (bpm INTEGER,songname TEXT);";
db.execSQL(CREATE_TABLE_COUNTRIES);
Log.e("media","table created");
ContentValues values = new ContentValues();
for(int i=0;i<proj.length;i++){
values.put("bpm", 0);
values.put("songname", proj[i]);
db.insert("songs", null, values);
}
Log.e("media","insered");
Cursor cx = db.rawQuery("select * from songs" , null);
if (cx != null ) {
if (cx.moveToFirst()) {
do { int bpm=cx.getInt(0);
String songname =cx.getString(1);
Log.e("songs","bpm "+bpm+" songname "+songname);
}while (cx.moveToNext());
}
}
db.close();
musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,proj, null, null, null);
Log.e("media1",""+musiccursor);
my log cat output is :
05-02 12:28:02.716: ERROR/media(957): 4
05-02 12:28:03.156: ERROR/media(957): table created
05-02 12:28:03.986: ERROR/media(957): insered
05-02 12:28:03.986: ERROR/songs(957): bpm 0 songname _id
05-02 12:28:03.986: ERROR/songs(957): bpm 0 songname _data
05-02 12:28:03.986: ERROR/songs(957): bpm 0 songname _display_name
05-02 12:28:03.986: ERROR/songs(957): bpm 0 songname _size
05-02 12:28:04.026: ERROR/media1(957): android.content.ContentResolver$CursorWrapperInner@4357b868
please assist me.
A: You should use a 'SQLiteOpenHelper' to manage your Database tables. Then, you can use it's functions 'getReadableDatabase()' and 'getWriteableDatabase()', which return an 'SQLiteDatabase'. That's the common way of doing this.
Check Googles Tutorial on this.
| |
doc_23530911
|
imgur.com/a/1wt4N [Screenshot of app]
private String[] vocSpinner;
private String[] popSpinner;
private List<Standard> standardList = new ArrayList<>();
private RecyclerView recyclerView;
private StandardsAdapter sAdapter;
private CheckBox cb1;
private CheckBox cb2;
cb1 = (CheckBox) getActivity().findViewById(R.id.pushUp);
cb2 = (CheckBox) getActivity().findViewById(R.id.sitUp);
this.vocSpinner = new String[]{
"CDO/Diver/Gds/Fitness Spec", "Combat/Service"
};
this.popSpinner = new String[]{
"NSmen", "Regular/NSF", "Pre-enlistee"
};
final Spinner v = (Spinner) getActivity().findViewById(R.id.spinner_Voc);
final Spinner p = (Spinner) getActivity().findViewById(R.id.spinner_PopGp);
ArrayAdapter<String> adapterV = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, vocSpinner);
v.setAdapter(adapterV);
ArrayAdapter<String> adapterP = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, popSpinner);
p.setAdapter(adapterP);
v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
standardList.clear();
cb1.setEnabled(true);
cb2.setEnabled(true);
switch (position) {
case 0:
if (p.getSelectedItem().equals("NSmen")) {
cb1.setChecked(false);
cb2.setChecked(false);
addStandardToList("Gold - $500", ">89pts");
addStandardToList("Silver - $300", ">74pts");
addStandardToList("Incentive - $200", ">60pts");
addStandardToList("Pass", ">50pts");
sAdapter.notifyDataSetChanged();}
else if (p.getSelectedItem().equals("Regular/NSF")) {
cb1.setChecked(false);
cb2.setChecked(false);
addStandardToList("Gold - $300", ">89pts");
addStandardToList("Silver - $200", ">74pts");
addStandardToList("Incentive", "NA");
addStandardToList("Pass", ">60pts");
sAdapter.notifyDataSetChanged();
A: Get the cb from the following code:
View myView = list.getChildAt(index);
CheckBox checkItem = (CheckBox) myView.findViewById(R.id.checkboxId);
checkItem.setChecked(false);
A: in your onItemSelected listener of your spinner you have done
cb1.setEnabled(true);
cb2.setEnabled(true);
Below that you should also do
cb1.setChecked(false);
cb2.setChecked(false);
also if no checkbox is checked, it is manually selecting the same values of your spinner that were previously selected so that your selection listener of spinner is called and your array is repopulated based on spinner values. For that do the following in your else -
String getSelectedItemP = p.getSelectedItem().toString();
p.setSelection(((ArrayAdapter<String>)p.getAdapter()).getPosition(getSelectedItemP));
String getSelectedItemV = v.getSelectedItem().toString();
v.setSelection(((ArrayAdapter<String>)p.getAdapter()).getPosition(getSelectedItemV));
So your one if condition onCheckedChanged would look like
if (v.getSelectedItem().equals("CDO/Diver/Gds/Fitness Spec") || v.getSelectedItem().equals("Combat/Service") && p.getSelectedItem().equals("NSmen")) {
if (cb1.isChecked() && cb2.isChecked()) {
addStandardToList("Gold - $500", "NA");
addStandardToList("Silver - $300", "NA");
addStandardToList("Incentive - $200", "NA");
addStandardToList("Pass", ">25pts");
sAdapter.notifyDataSetChanged();
} else if (cb1.isChecked() || cb2.isChecked()) {
addStandardToList("Gold - $500", "NA");
addStandardToList("Silver - $300", "NA");
addStandardToList("Incentive - $200", "NA");
addStandardToList("Pass", ">38pts");
sAdapter.notifyDataSetChanged();
}else{
// select spinner again here manually.
String getSelectedItemP = p.getSelectedItem().toString();
p.setSelection(((ArrayAdapter<String>)p.getAdapter()).getPosition(getSelectedItemP));
String getSelectedItemV = v.getSelectedItem().toString();
v.setSelection(((ArrayAdapter<String>)p.getAdapter()).getPosition(getSelectedItemV));
}
}
| |
doc_23530912
|
[price ELEPHANT]
[price MONKEY_345]
[price TIGER.3TAIL]
where the word in caps (with the extension, if any) is the product SKU.
I've run a database query for SKU and PRICE, so now I want to replace the shortcode in my text to the actual price of the item.
[price ELEPHANT] becomes 46.97
1.) I have been working with preg_replace, but can't get it to work with "." or "_" in the SKU:
$text = '<p>We have the price: [price CANOPY3.75B]. This is some more text.</p>';
$pattern = '/\[(\w+) (\w+)\]/';
$replacement = '$2';
echo preg_replace($pattern, $replacement, $text);
2.) Once I identify the shortcode SKU value, how do I use it to search the array for the associated price?
(Hope I did the code blocks OK -- this is my first post here.)
A: Let's say you have the following array with the "name-price" pairs:
$prices = array('ELEPHANT' => 46.97, 'CANOPY3.75B' => 20.35, 'TIGER.3TAIL' => 30 ... etc.);
Then you can use the following piece of code:
$prices = array('ELEPHANT' => 46.97, 'CANOPY3.75B' => 20.35, 'TIGER.3TAIL' => 30,);
$text = '<p>We have the price: [price CANOPY3.75B]. This is some more text.</p>';
$pattern = '/\[price (.*?)\]/';
echo preg_replace_callback($pattern,
function($match)
{
global $prices;
return isset($prices[$match[1]]) ? $prices[$match[1]] : $match[1];
},
$text);
//output: We have the price: 20.35. This is some more text.
| |
doc_23530913
|
I am now trying to create a table for qualifications which has a one to many relationship with the consultants profile so one profile can have many qualifications.
For ease i here is a shorter version of the schema for the tables:
consultant_profile [
- id
- address line 1
- postcode
]
consultant_qualifications [
- id
- consultant_profile_id
- qualification
]
I have put this in my model for the consultant_profile
public function qualifications()
{
return $this->hasMany('ConsultantQualifications', 'consultant_profile_id');
}
and this in my consultant_qualifications model
public function profile()
{
return $this->belongsTo('ConsultantProfile',null,"consultant_profile_id");
}
I have tried it with putting in foreign/local keys and without.
What i expect the out come to be is i can look in the relations array of user object and see the profile object, i could then look into profile object and in its relations array i should see qualifications object
But i don't, any reason why?
| |
doc_23530914
|
The first thing I tried:
Grid layout is a layout I created in Qt Creator.
#include <QProcess>
#include <QWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QTimer>
#include "glwidget.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
GLWidget *glwidget = new GLWidget(); // This is mandatory. No problems here.
QTimer *timer = new QTimer(this); // Need this for the example to work.
timer->setInterval(10); // Also necessary.
ui->gridLayout->addWidget(glwidget);
Which compiles, but then promptly crashes with a segmentation fault.
ui->gridLayout->addWidget(new GLWidget);
Segfaults the same way.
The debugger points me toward line 104 of qgridlayout.h:
inline void addWidget(QWidget *w) { QLayout::addWidget(w); }
Not sure what to make of that. Perhaps the QGLWidget wants to do something before I call ui->setupUi(this)? Perhaps it can't add the widget to the layout for some reason?
Of course if I comment out the line where I am added the widget, the program works flawlessly.
Any ideas for what's going on here?
Edit: I have fixed this. It was problem with order of operations - I called updateui too quickly.
A: I'm not sure, but I think the problem is with the following line:
ui->gridLayout->addWidget(GLWidget);
I think, you should write it as follows:
ui->gridLayout->addWidget(glwidget);
A: The setupUi function in the generated form class initializes all variables of the form class, so using the variables before the form is initialized is undefined behaviour, since the variables contain garbage.
So the solution is to call:
ui->setupUi(this)
Before any call that uses variables in the ui object.
A: // declare glwidget as member of your class
GLWidget *glwidget;
//in constructor use
glwidget = new GLWidget();
| |
doc_23530915
|
For example, let's say the text is:
arn:aws:dfasdfasdf/asdfa:start:CaptureThis/end
The output should be: CaptureThis
And the two tokens are: :start: and /end
The closest I could get was using this regex:
INPUT="arn:aws:dfasdfasdf/asdfa:start:CaptureThis/end"
VALUE=$(echo "${INPUT}" | sed -e 's/:start:\(.*\)\/end/\1/')
... but this returns most of the string: arn:aws:dfasdfasdf/asdfa:start:CaptureThis/end
How do I get all of the other text out of the way?
A: You could use (GNU) grep with Perl regular expressions (look-arounds) and the -o option to only return the match:
$ grep -Po '(?<=:start:).*(?=/end)' <<< 'arn:aws:dfasdfasdf/asdfa:start:CaptureThis/end'
CaptureThis
A: Try this:
$ sed 's/^.*:start:\(.*\)\/end.*$/\1/' <<<'arn:aws:dfasdfasdf/asdfa:start:CaptureThis/end'
CaptureThis
The problem with your approach was that you only replaced part of the input line, because your regex didn't capture the entire line.
Note how the command above anchors the regex both at the beginning of the line (^.*) and at the end (.*$) so as to ensure that the entire line is matched and thus replaced.
A: You could use :
VALUE=$(echo "${INPUT}" | sed -e 's/.*:start:\(.*\)\/end.*/\1/')
If the tokens are liable to change, you could use variables - but since "/end" has a "/", that could lead to sed getting confused, so you'd probably want to change its delimiter to some non-conflicting character (like a "?"), so :
TOKEN1=":start:"
TOKEN2="/end"
VALUE=$(echo "${INPUT}" | sed -e "s?.*$TOKEN1\(.*\)$TOKEN2.*?\1?")
A: There is no need for any external utilities, bash parameter-expansion will handle it all for you:
INPUT="arn:aws:dfasdfasdf/asdfa:start:CaptureThis/end"
token=${INPUT##*:}
echo ${token%/*}
Output
CaptureThis
| |
doc_23530916
|
"Stage XXX": {
"Type": "Task",
"ResultPath": null,
"Resource": "arn:aws:states:::ecs:runTask.sync",
"Parameters": {
"LaunchType": "FARGATE",
"Cluster": "<EXPORTED_NAME_FARGATE_CLUSTER_ARN>",
"TaskDefinition": "<EXPORTED_NAME_FARGATE_TASK_ARN>",
"NetworkConfiguration": {
"AwsvpcConfiguration": {
"Subnets": ["<SUBNET-0>", "<SUBNET-1>"],
"AssignPublicIp": "ENABLED"
}
},
"Overrides": {
"ContainerOverrides": [
{
"Name": "spinarak-process-fargate-task-container",
"Environment": [
{
"Name": "REDO_INFER",
"Value.$": "$.RedoInfer"
},
{
"Name": "REDO_EDM",
"Value.$": "$.RedoEdm"
}
]
}
]
}
},
"Retry": [
{
"ErrorEquals": ["States.ALL"],
"IntervalSeconds": 3,
"MaxAttempts": 0,
"BackoffRate": 1.5
}
],
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"ResultPath": "$.taskerror",
"Next": "Publish Failure"
}
],
"Next": "Stage YYY"
},
A: Sorry. Just noticed that the public IP is removed after container is stopped. There is a public IP when container is still running.
| |
doc_23530917
|
x= "{\"device_codename\": \"nikel\", \"brand\": \"Xiaomi\"}"
y= {"percent_incoming_nighttime": 0.88, "percent_outgoing_daytime": 9.29}
The result
device_codename brand percent_incoming_nighttime percent_outgoing_daytime
nikel Xiaomi 0.88 9.29
I have tired using grep but iam getting errors any suggestion?
grep("device_codename", x, perl=TRUE, value=TRUE)
A: This is possibly JSON format. There are tools to handle those.
library(jsonlite)
x = "{\"device_codename\": \"nikel\", \"brand\": \"Xiaomi\"}"
y = '{"percent_incoming_nighttime": 0.88, "percent_outgoing_daytime": 9.29}'
> unlist(fromJSON(x))
device_codename brand
"nikel" "Xiaomi"
> unlist(fromJSON(y))
percent_incoming_nighttime percent_outgoing_daytime
0.88 9.29
A: After removing the braces ({}) and double quotes with gsub, read the substring after the : using read.csv into a data.frame and then change the column names with the substring i.e. before the :
v1 <- gsub('"|[{}]', "", c(x, y))
out <- read.csv(text=paste(gsub("\\w+:\\s+", "", v1), collapse=", "),
header=FALSE, stringsAsFactors = FALSE)
colnames(out) <- unlist(regmatches(v1, gregexpr("\\w+(?=:)", v1, perl = TRUE)))
out
# device_codename brand percent_incoming_nighttime percent_outgoing_daytime
#1 nikel Xiaomi 0.88 9.29
NOTE: No external packages used
Or using RJSONIO and tidyverse
library(tidyverse)
library(RJSONIO)
list(x, y) %>%
map(~ fromJSON(.x) %>%
as.list %>%
as_tibble) %>%
bind_cols
# A tibble: 1 x 4
# device_codename brand percent_incoming_nighttime percent_outgoing_daytime
# <chr> <chr> <dbl> <dbl>
#1 nikel Xiaomi 0.88 9.29
data
x <- "{\"device_codename\": \"nikel\", \"brand\": \"Xiaomi\"}"
y <- "{\"percent_incoming_nighttime\": 0.88, \"percent_outgoing_daytime\": 9.29}"
A: completed jsonlite solution (Roman Luštrik)
library(jsonlite)
library(dplyr)
xx_x= "{\"device_codename\": \"nikel\", \"brand\": \"Xiaomi\"}"
xx_y= "{\"percent_incoming_nighttime\": 0.88, \"percent_outgoing_daytime\": 9.29}"
c(jsonlite::fromJSON(xx_x), jsonlite::fromJSON(xx_y)) %>%
reshape2::melt() %>% mutate(myrow = 1) %>%
spread(L1, value)
result
myrow brand device_codename percent_incoming_nighttime percent_outgoing_daytime
1 1 Xiaomi nikel 0.88 9.29
| |
doc_23530918
|
The problem I have is that I need to detect the width and height of the image from the byte array so I can adjust adjust the texture size and avoid image stretching on the unity scene at run-time.
Do you know how I could use a library or function of some kind to maybe create a temp image from the image byte array and then see the desired width and height before I create the sprite and apply the texture?
I've found solutions in Java but can't seen to get it working by adapting in c#.
A: When Texture2D.LoadImage is called, it will automatically replace the Texture2D instance with the size of the image. You can then grab the width and height from the Texture2D instance and pass it to the Sprite.Create function.
Load your image to byte array
byte[] imageBytes = loadImage(savePath);
Create new Texture2D
Texture2D texture = new Texture2D(2, 2);
Load it into a Texture2D.
After LoadImage is called, 2x2 will be replaced with the size of that image.
texture.LoadImage(imageBytes);
Your image component
Image im = GetComponent<Image>();
You can create a new Rect with it and then pass it to your Sprite function to create new Sprite.
im.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
Read more about the Texture2D.LoadImage function here.
You just need Texture2D.width and Texture2D.height variables.
| |
doc_23530919
|
My solution structure looks like this:
Project A: dependency factory using Unity with unity xml config file.
Project B: Several types that are implementations of interfaces used in Unity config. These types reference Microsoft.Sharepoint.dll.
Project C: Other implementation types for Unity. No reference to Sharepoint dlls.
During the unit test execution in Visual Studio 2010 I have problems.
When I try to load my Unity configuration for any of Project B types it fails to load and causes the whole container to fail it's configuration.
After several attempts to solve the problem setting and checking the references of project B I noticed that Unity works fine if all my assemblies are installed in GAC.
If I remove them from GAC the loading of Unity config fails.
If I try and call the Unity Resolve method from a simple Windows application Unity loads everything fine regardless of whether all my assemblies are in GAC or not.
So what settings of assembly resolver am I missing in my Visual Studio Test configuration so Unity works without need of GAC deployment?
A: I have found my problem.
I was missing several output files in the Out folder of the Visual Studio test.
All I had to do was to add a new deployment folder in the Test settings.
I went to local.testSettings, then selected Deployment and then added my bin folder as deployment item.
Now Visual Studio copies all files from the Bin to the Out folder and everything works like charm.
Hope it will save some time to someone in the same situation like mine :)
| |
doc_23530920
|
On our development server we are running Windows 2008R2 with IIS 7.5 on a virtual x64 instance with 8GB RAM.
Here I call a WCF method that uses ThreadPool.QueueUserWorkItem to process a large amount of hierarchical data. This works fine, and work rather fast (a 270 MB XML is read an processed producing 190.035 records within 379 seconds). The client is done calling the method about 250 seconds in.
Now the same "workflow" on Windows Azure is a whole other case. Although similar (Large instance in Round Robin configuration), Windows Azure stop within seconds the client disconnect. This means that only 160.055 records is written and far slower - 917 seconds. The problem here is, that I miss around 30.000 records which should now be queued on the two Azure instances, but it seems like - on client disconnect - to abandon the remaining work.
The client uses HttpWebRequest for communication and both solutions run .NET 4.0.
What is that I am missing out on here?
Thanks in advance for any help regarding this issue.
A: My bad guys - I simply could not in my wildest imagination foresee that Windows Azure would be so slow .. so by increasing the HttpWebRequest from 2 minutes to 30 minutes I was able to achieve the same data volume as in our development environment.
So - I will not delete the question - but let this stand as a reference for you soon to come Azure guys.
I am positive that Azure (and other cloud providers) is the future, but from Denmark to "North Europe" the latency is high - and SQL Azure has yet to prove it can perform when talking OLTP and normalized databases.
DEVELOPMENT (VIRTUAL ENVIRONMENT)
190.335 records from a 299 MB file took 379 seconds on a single instance
WINDOWS AZURE (NORTH EUROPE)
190.335 records from a 299 MB file took 1.400 seconds on two LARGE instances
The good news is, that WCF and ThreadPool work flawlessly and no special considerations (except a high timeout) is necessary.
Just to clarify, the 299MB file is split up in multiple REST calls to the server, in a format similiar to this one:
<?xml version="1.0" encoding="UTF-8"?>
<HttpPost absolutePath="A/B/C/D/E/OO">
<Parameters xmlns="http://somenamespace">
<A>Package</A>
<B>100</B>
<C>Generic</C>
<D>ReceiverParty</D>
<E>
<F xmlns="http://somenamespace">
<G xmlns="http://somenamespace/Product">Long Text</G>
<H xmlns="http://somenamespace/Product">1</H>
<I xmlns="http://somenamespace/Product">PK</I>
<J xmlns="http://somenamespace/Product">5995</J>
<K xmlns="http://somenamespace/Product">
<L xmlns="http://somenamespace/P/Q">Discount</L>
<M xmlns="http://somenamespace/P/Q">1000</M>
<N xmlns="http://somenamespace/P/Q">6995</N>
</K>
</F>
</E>
<OO>
<O>
<A>Product</A>
<B>100</B>
<C>Generic</C>
<D>ReceiverParty</D>
<E>
<F xmlns="http://somenamespace">
<G xmlns="http://somenamespace/Product">Long Text</G>
<H xmlns="http://somenamespace/Product">1</H>
<I xmlns="http://somenamespace/Product">PK</I>
<J xmlns="http://somenamespace/Product">5995</J>
<K xmlns="http://somenamespace/Product">
<L xmlns="http://somenamespace/P/Q">Discount</L>
<M xmlns="http://somenamespace/P/Q">1000</M>
<N xmlns="http://somenamespace/P/Q">6995</N>
</K>
</F>
</E>
</O>
</OO>
</Parameters>
</HttpPost>
| |
doc_23530921
|
function add_content_after_addtocart_button_func() {
echo '
<div class="wsbl_line"><a href="http://line.me/R/msg/text/website.com"
title="share using Line" rel="nofollow"
class="wp_social_bookmarking_light_a"><img src="sample-image.png"
width="135" height="30" class="wp_social_bookmarking_light_img"></a></div>';
}
Upon adding the following Google Analytics event tracking code to the above code the site breaks.
function add_content_after_addtocart_button_func() {
echo '
<div class="wsbl_line"><a href="http://line.me/R/msg/text/website.com"
title="share using Line" rel="nofollow"
class="wp_social_bookmarking_light_a" onClick="ga('send', 'event', 'social', 'line-button-click', 'line-button');"><img src="sample-image.png"
width="135" height="30" class="wp_social_bookmarking_light_img"></a></div>';
}
I've successfully tested the tracking code by putting it directly in a page
<a href="website.com" onClick="ga('send', 'event', 'social', 'line-button-
click', 'line-button');">anchor text</a>
What am I doing wrong?
A: If you open code with single quote and use them in code you want to echo, you need to escape it, like this:
function add_content_after_addtocart_button_func() {
echo '
<div class="wsbl_line"><a href="http://line.me/R/msg/text/website.com"
title="share using Line" rel="nofollow"
class="wp_social_bookmarking_light_a" onClick="ga(\'send\', \'event\',
\'social\', \'line-button-click\', \'line-button\');"><img src="sample-
image.png"
width="135" height="30" class="wp_social_bookmarking_light_img"></a></div>';
}
Even if you open echo with " doublequotes it will break since there are double quostes in code you are echoing. I advise you to use some text editor with php syntax highlighting to see where it breaks.
Try the code i gave you,
Regards
| |
doc_23530922
|
<timer end-time="{{timelimit.timeLimitDate}}">{{days}} days, {{hours}} hours, {{minutes}} minutes, {{seconds}} seconds.</timer>
the error:
Unhandled Promise rejection: Template parse errors:
'timer' is not a known element:
1. If 'timer' is an Angular component, then verify that it is part of
this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("ate}}">{{days}} days, {{hours}} hours, {{minutes}} minutes, {{seconds}} seconds.</timer>-->
Did anyone know what need to do, thanks a lot~
A: You can not use above timer with Ionic 3.Because it uses AngularJS.You need to find an Angular module for that.
I think you can use this ng2-simple-timer module on your Ionic app.
Add SimpleTimer into module providers (eg. app.module.ts).
import { SimpleTimer } from 'ng2-simple-timer';
@NgModule({
providers: [SimpleTimer]
})
More info is here.
| |
doc_23530923
|
The implementation is permitted to forego some of the complexities with threading as it enforces that only one thread will ever place items into the queue and only one thread will ever take them out (this is by design).
The problem is that sometimes, the Take() will skip an item as if it was never there and in my tests I'll get "Expected: 736 But was: 737". I can't see anywhere in this code that that kind of effect would occur; Put will only ever place after the very last item (so it shouldn't be affecting this.m_Head directly) and Take is using Interlocked.Exchange to take the item from the head.
How does this implementation permit the issue to occur?
Implementation:
using System;
using System.Threading;
#pragma warning disable 420
namespace Tychaia.Threading
{
public class TaskPipeline<T>
{
private int? m_InputThread;
private int? m_OutputThread;
private volatile TaskPipelineEntry<T> m_Head;
/// <summary>
/// Creates a new TaskPipeline with the current thread being
/// considered to be the input side of the pipeline. The
/// output thread should call Connect().
/// </summary>
public TaskPipeline()
{
this.m_InputThread = Thread.CurrentThread.ManagedThreadId;
this.m_OutputThread = null;
}
/// <summary>
/// Connects the current thread as the output of the pipeline.
/// </summary>
public void Connect()
{
if (this.m_OutputThread != null)
throw new InvalidOperationException("TaskPipeline can only have one output thread connected.");
this.m_OutputThread = Thread.CurrentThread.ManagedThreadId;
}
/// <summary>
/// Puts an item into the queue to be processed.
/// </summary>
/// <param name="value">Value.</param>
public void Put(T value)
{
if (this.m_InputThread != Thread.CurrentThread.ManagedThreadId)
throw new InvalidOperationException("Only the input thread may place items into TaskPipeline.");
// Walk the queued items until we find one that
// has Next set to null.
var head = this.m_Head;
while (head != null)
{
if (head.Next != null)
head = head.Next;
if (head.Next == null)
break;
}
if (head == null)
this.m_Head = new TaskPipelineEntry<T> { Value = value };
else
head.Next = new TaskPipelineEntry<T> { Value = value };
}
/// <summary>
/// Takes the next item from the pipeline, or blocks until an item
/// is recieved.
/// </summary>
/// <returns>The next item.</returns>
public T Take()
{
if (this.m_OutputThread != Thread.CurrentThread.ManagedThreadId)
throw new InvalidOperationException("Only the output thread may retrieve items from TaskPipeline.");
// Wait until there is an item to take.
var spin = new SpinWait();
while (this.m_Head == null)
spin.SpinOnce();
// Return the item and exchange the current head with
// the next item, all in an atomic operation.
return Interlocked.Exchange(ref this.m_Head, this.m_Head.Next).Value;
}
}
}
#pragma warning restore 420
Failing Test:
[Test]
public void TestPipelineParallelTo100()
{
var random = new Random();
var pipeline = new TaskPipeline<int>();
var success = true;
int expected = 0, actual = 0;
ThreadStart processor = () =>
{
pipeline.Connect();
for (int i = 0; i < 100; i++)
{
var v = pipeline.Take();
if (v != i)
{
success = false;
expected = i;
actual = v;
break;
}
Thread.Sleep(random.Next(1, 10));
}
};
var thread = new Thread(processor);
thread.Start();
for (int i = 0; i < 100; i++)
{
pipeline.Put(i);
Thread.Sleep(random.Next(1, 10));
}
thread.Join();
if (!success)
Assert.AreEqual(expected, actual);
}
A: If you assign the value of m_Head.Next after it is read in Take for passing to Interlocked.Exchange(ref this.m_Head, this.m_Head.Next), the pointer will be lost because the only way to access it was through m_Head.
*
*Take reads m_Head.Next (==null)
*Put writes m_Head.Next (!=null)
*Take writes m_Head (==null)
Edit: This should work. I used a non-null sentinel value and Interlocked.CompareExchange to make sure Put doesn't try to reuse an entry that Take is already removing.
Edit 2: Tweaks to Take.
Edit 3: I believe I still need to add a goto retry; in Put if the identified tail is Entry.Sentinel.
using System;
using System.Threading;
#pragma warning disable 420
namespace Tychaia.Threading
{
public class TaskPipeline<T>
{
private int? m_InputThread;
private int? m_OutputThread;
private volatile Entry m_Head;
private sealed class Entry
{
public static readonly Entry Sentinel = new Entry(default(T));
public readonly T Value;
public Entry Next;
public Entry(T value)
{
Value = value;
Next = null;
}
}
/// <summary>
/// Creates a new TaskPipeline with the current thread being
/// considered to be the input side of the pipeline. The
/// output thread should call Connect().
/// </summary>
public TaskPipeline()
{
this.m_InputThread = Thread.CurrentThread.ManagedThreadId;
this.m_OutputThread = null;
}
/// <summary>
/// Connects the current thread as the output of the pipeline.
/// </summary>
public void Connect()
{
if (this.m_OutputThread != null)
throw new InvalidOperationException("TaskPipeline can only have one output thread connected.");
this.m_OutputThread = Thread.CurrentThread.ManagedThreadId;
}
/// <summary>
/// Puts an item into the queue to be processed.
/// </summary>
/// <param name="value">Value.</param>
public void Put(T value)
{
if (this.m_InputThread != Thread.CurrentThread.ManagedThreadId)
throw new InvalidOperationException("Only the input thread may place items into TaskPipeline.");
retry:
// Walk the queued items until we find one that
// has Next set to null.
var head = this.m_Head;
while (head != null)
{
if (head.Next != null)
head = head.Next;
if (head.Next == null)
break;
}
if (head == null)
{
if (Interlocked.CompareExchange(ref m_Head, new Entry(value), null) != null)
goto retry;
}
else
{
if (Interlocked.CompareExchange(ref head.Next, new Entry(value), null) != null)
goto retry;
}
}
/// <summary>
/// Takes the next item from the pipeline, or blocks until an item
/// is recieved.
/// </summary>
/// <returns>The next item.</returns>
public T Take()
{
if (this.m_OutputThread != Thread.CurrentThread.ManagedThreadId)
throw new InvalidOperationException("Only the output thread may retrieve items from TaskPipeline.");
// Wait until there is an item to take.
var spin = new SpinWait();
while (this.m_Head == null)
spin.SpinOnce();
// Return the item and exchange the current head with
// the next item, all in an atomic operation.
Entry head = m_Head;
retry:
Entry next = head.Next;
// replace m_Head.Next with a non-null sentinel to ensure Put won't try to reuse it
if (Interlocked.CompareExchange(ref head.Next, Entry.Sentinel, next) != next)
goto retry;
m_Head = next;
return head.Value;
}
}
}
| |
doc_23530924
|
Versions that are installed in my system
Python 3.8.3 -- envvar set to python3
PyCharm 2020.1.2 (Community Edition)
Python 2.7(due to maya pyside2) -- envvar set to python
As per python docs
https://docs.python.org/3/library/venv.html#creating-virtual-environments
Deprecated since version 3.6: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is deprecated in Python 3.6.
Changed in version 3.5: The use of venv is now recommended for creating virtual environments.
I require PyQt5 for my current proj
and python3.8.3 was best suited so decided to go with it
and pycharm as my IDE
1) so i decided to create a virtual env through it but it prompts an error.
in case if the image is not displayed error was
2020.1.1\plugins\python-ce\helpers\packaging_tool.py pyvenv
Error:[WinError 2] The system cannot find the file specified
I don't get it why pycharm is not able to recognize the version of python3.5 and above.
2) so as per above docs i started searching venv for couple of hours and came across many pages eg: https://www.c-sharpcorner.com/article/steps-to-set-up-a-virtual-environment-for-python-development/
and referred the page and installed through pycharm the virtualenv and virtualenvwrapper-win and began the process again but this time through terminal and worked like a charm. env was created.
but as we know the python.exe is required in scripts folder to run anything but that was missing
3) that brings me to 3rd point i enforced the python persion with virtualenv path/venv -p python3.exe but still no sign of python in the environment.
and if i activate the environment "activate.bat" works fine
pip list in terminal
prompts me
Fatal error in launcher: Unable to create process using '"D:\All_Projs\Maya_Projs\succinct_save\venv\Scripts\python.exe" "D:\All_Projs\Maya_Projs\succinct_save\venv\Scripts\pip.exe" list': The system cannot find the file specified
Help appreciated
Thank You.
| |
doc_23530925
|
g = TinkerGraph.open().traversal()
first_generation = g.addV('person').property('id', '1').next()
second_generation = g.addV('person').property('id', '2').next()
third_generation = g.addV('person').property('id', '3').next()
third_generation_1 = g.addV('person').property('id', '4').next()
fourth_generation = g.addV('person').property('id', '5').next()
g.addE('child').from(first_generation).to(second_generation)
g.addE('child').from(second_generation).to(third_generation)
g.addE('child').from(second_generation).to(third_generation_1)
g.addE('child').from(third_generation).to(fourth_generation)
Here, I want to fetch the list of all people with the number of children they have.
[{'id': 1, 'children': 1}, {'id': 2, 'children': 2}]
I read about sideEffect but can't seem to append the result of sideEffect to the output.
Any suggestions on how we can achieve the desired output ?
A: You should probably use project()
gremlin> g.V().hasLabel('person').
......1> project('id','children').
......2> by('id').
......3> by(out('child').count())
==>[id:1,children:1]
==>[id:2,children:2]
==>[id:3,children:1]
==>[id:4,children:0]
==>[id:5,children:0]
It takes each vertex and transforms it into a Map of the specified keys. The by() modulators then specify what the values of those keys should be.
| |
doc_23530926
|
I need to load the Mode (Dev, Test, Prod) which my Play application is running into the Main process Application, here:
val app: Application = GuiceApplicationBuilder().build().
This is what I have:
object ConsumersApp {
def main(args: Array[String]): Unit = {
val app: Application = GuiceApplicationBuilder()
.loadConfig(env => Configuration.load(env))
.build()
//...
}
}
But .loadConfig(env => Configuration.load(env)) actually returns Mode.Test even when in production environment.
A: You can pass the -main option to the target/universal/stage/bin command in your Procfile. For example:
worker: target/universal/stage/bin/play-app -main com.example.MyClass
I'm not sure if there is a specification for this flag, but the code is on Github
| |
doc_23530927
|
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'D:\database.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
but when i try to do syncdb i get the following:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
438, in execute_manager
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 191,
in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 220,
in execute
output = self.handle(*args, **options)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 351,
in handle
return self.handle_noargs(**options)
File "C:\Python27\lib\site-packages\django\core\management\commands\syncdb.py"
, line 56, in handle_noargs
cursor = connection.cursor()
File "C:\Python27\lib\site-packages\django\db\backends\__init__.py", line 250,
in cursor
cursor = self.make_debug_cursor(self._cursor())
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line
207, in _cursor
self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file
Any idea what's going on?
Notice that I tried to change the db name (location) many times but it didn't work ...
A: Use forward slashes or r'' strings to begin with.
'default': {
# [... snip ...]
'NAME': 'D:/database.db',
# (or...) 'NAME': r'D:\database.db',
# [... snip ...]
}
Additionally you need to ensure the entire directory your Sqlite file is in is writable (in this case D:/), as Sqlite needs to write its journal file next to the database file.
A: This works for me
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'c:/projects/blog/first.db',
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Not used with sqlite3.
'PORT': '', # Not used with sqlite3.
}
}
A: Try using only the name of the database file (no path). By default, Django will place it in the same directory as manage.py
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'database.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
| |
doc_23530928
|
At some point, I want to add a feature that allows users to float TabItems and dock them back into the TabControl much along the lines of what you can do in Visual Studio. This feature will allow users to more easily compare documents and copy/paste between them, etc.
I have some general ideas on how to go about doing this. The TabControl has its ItemsSource bound to a list of document view models.
To float the tab:
*
*Add a Thumb control to the tab strip area of the TabItem.
*When the user drags the Thumb, the associated document view model is removed from the TabControl list.
*A separate document Window is brought up, bound with the document view model, to display/edit that document.
To dock the tab:
*
*Add a DragOver event handler in the TabControl to recognise a document Window dragging over the tab strip area.
*The associated document view model is added to the TabControl list.
*The document Window is closed.
Are there any examples out there on how to do this, or do you have an approach to do this?
Thanks.
A: If you can't find or don't want to use a pre-existing control, I would highly recommend Bea Stollnitz's article about dragging and dropping between databound controls. You will probably have to alter it a bit to work with a DockPanel to identify what DockPanel.Dock the databound object should use, however I've found the code easy to alter in the past.
You would then setup two databound controls, such as a TabControl and a DockPanel, and when dragging/dropping between the two you are actually dragging/dropping the databound items between the ItemsSources.
A: I finally got around to implementing this feature, and I used AvalonDock 2.0, which is MVVM friendly. All I needed to do was to replace the TabControl with a DockingManager and modify a few Styles.
The DockingManager setup (I only have documents, not tools, etc.):
<avalonDock:DockingManager x:Name="tabDesigner" DocumentsSource="{Binding Items}">
<avalonDock:DockingManager.LayoutItemContainerStyle>
<Style TargetType="{x:Type avalonDockControls:LayoutItem}" BasedOn="{StaticResource DocumentItem}"/>
</avalonDock:DockingManager.LayoutItemContainerStyle>
<avalonDock:DockingManager.DocumentPaneControlStyle>
<Style TargetType="{x:Type avalonDockControls:LayoutDocumentPaneControl}" BasedOn="{StaticResource DocumentPane}"/>
</avalonDock:DockingManager.DocumentPaneControlStyle>
<avalonDockLayout:LayoutRoot>
<avalonDockLayout:LayoutPanel Orientation="Horizontal">
<avalonDockLayout:LayoutDocumentPane/>
</avalonDockLayout:LayoutPanel>
</avalonDockLayout:LayoutRoot>
</avalonDock:DockingManager>
I didn't need to use AvalonDock's template selectors, I was able to use the DataTemplates that were already set up for the previous TabControl.
I modified the LayoutItem, LayoutDocumentPaneControl, and LayoutDocumentTabItem Styles to do the extra binding to the view models and other layout differences (it took a little while to figure out how to bind to the view models that are within AvalonDock's model):
<Style x:Key="DocumentItem" TargetType="{x:Type avalonDockControls:LayoutItem}">
<Setter Property="Title" Value="{Binding Model.TabTitle}"/>
<Setter Property="CloseCommand" Value="{Binding Model.CloseConfirmCommand}"/>
<Setter Property="IsSelected" Value="{Binding Model.IsSelected, Mode=TwoWay}"/>
</Style>
<Style x:Key="DocumentPane" TargetType="{x:Type avalonDockControls:LayoutDocumentPaneControl}">
...
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type avalonDockControls:LayoutDocumentPaneControl}">
<Grid ClipToBounds="true" SnapsToDevicePixels="true" KeyboardNavigation.TabNavigation="Local">
...
<Grid Panel.ZIndex="1" Background="{DynamicResource TabControlHeaderBrush}" >
...
<avalonDockControls:DocumentPaneTabPanel x:Name="HeaderPanel" Grid.Column="0" IsItemsHost="true" Margin="4,0,16,0" Grid.Row="0" KeyboardNavigation.TabIndex="1"/>
<avalonDockControls:DropDownButton
...
Style="{DynamicResource ToolBarHorizontalOverflowButtonStyle}"
Grid.Column="1">
...
</avalonDockControls:DropDownButton>
</Grid>
<Border x:Name="ContentPanel"
...
CornerRadius="3">
<Border
...
>
<Border
...
>
<ContentPresenter x:Name="PART_SelectedContentHost"
ContentSource="SelectedContent"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</Border>
</Border>
</Grid>
<ControlTemplate.Triggers>
...
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type TabItem}">
...
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<ContentPresenter
x:Name="Content"
ContentSource="Header"
...
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<avalonDockControls:LayoutDocumentTabItem Model="{Binding}"/>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<avalonDockControls:LayoutDocumentControl Model="{Binding}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type avalonDockControls:LayoutDocumentTabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type avalonDockControls:LayoutDocumentTabItem}">
<ControlTemplate.Resources>
...
</ControlTemplate.Resources>
<Grid x:Name="grid" Margin="8,1,8,0">
...
<Grid RenderTransformOrigin="0.5,0.5">
...
<StackPanel Orientation="Horizontal" Margin="3,0,2,0">
<ContentPresenter x:Name="TabContent" Content="{Binding Model, RelativeSource={RelativeSource TemplatedParent}}" TextBlock.Foreground="{DynamicResource UnselectedTabText}"
ContentTemplate="{Binding DocumentHeaderTemplate, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type avalonDock:DockingManager}, Mode=FindAncestor}}"
ContentTemplateSelector="{Binding DocumentHeaderTemplateSelector, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type avalonDock:DockingManager}, Mode=FindAncestor}}"
Margin="5,2,5,2"/>
<Button
x:Name="TabItemButton"
Command="{Binding Path=Model.Content.CloseConfirmCommand, RelativeSource={RelativeSource TemplatedParent}}"
Content="X"
...
/>
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="{Binding Model.Content.CloseTabLabel, RelativeSource={RelativeSource TemplatedParent}}" Command="{Binding Model.Content.CloseTab, RelativeSource={RelativeSource TemplatedParent}}" ToolTip="{Binding Model.Content.CloseTabToolTipLabel, RelativeSource={RelativeSource TemplatedParent}}"></MenuItem>
<MenuItem Header="{Binding Model.Content.CloseOtherTabsLabel, RelativeSource={RelativeSource TemplatedParent}}" Command="{Binding Model.Content.CloseOtherTabs, RelativeSource={RelativeSource TemplatedParent}}" ToolTip="{Binding Model.Content.CloseOtherTabsToolTipLabel, RelativeSource={RelativeSource TemplatedParent}}"></MenuItem>
<MenuItem Header="{Binding Model.Content.NextTabLabel, RelativeSource={RelativeSource TemplatedParent}}" Command="{Binding Model.Content.NextTab, RelativeSource={RelativeSource TemplatedParent}}" ToolTip="{Binding Model.Content.NextTabToolTipLabel, RelativeSource={RelativeSource TemplatedParent}}"></MenuItem>
</ContextMenu>
</StackPanel.ContextMenu>
</StackPanel>
</Grid>
</Grid>
<ControlTemplate.Triggers>
...
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This is an example of the end result:
| |
doc_23530929
|
This is my original code.
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
function showDiv() {
document.getElementById('loadingGif').style.display = "block"; //don't touch
setTimeout(function () {
document.getElementById('loadingGif').style.display = "none";//don't touch
}, time);
}
</script>
<div id="loadingGif" style="display:none">
<img src="https://mir-s3-cdn-cf.behance.net/project_modules/disp/35771931234507.564a1d2403b3a.gif">
</div>
It works however when I change CSS id into class and getElementById into getElementsByClassName it no longer works.
What am I doing wrong, please?
Thank you
A: The getElementsByClassName is a method of DOM and returns an array-like object.
In order to access to one element you have to use one for or foreach.
const array = document.getElementsByClassName('loadingGif');
Object.keys(array).forEach((key) => {
array[key].style.display = "block";
});
setTimeout(function () {
Object.keys(array).forEach((key) => {
array[key].style.display = "none";
});
}, time);
});
Try to use querySelector(".classname") instead getElementsByClassName.
A: Thank you @pilchard.
I have to replace document.getElementById('loadingGif') with document.querySelector('.loadingGif').
| |
doc_23530930
|
https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom
This draws a yellow star on a map, but I can't click the star and drag a map. I would like to be able to click the yellow star (so that a closed hand icon appears) and drag the map. I can do this while not hovering over the yellow star...how can I do this while hovering over the yellow star?
Thanks
A: Set clickable:false on the marker if you don't want it to accept mouse events.
| |
doc_23530931
|
My simplified Protractor configuration:
// protractor.conf.js
exports.config = {
baseUrl: 'http://localhost:8000',
seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: {
browserName: 'chrome',
},
framework: 'custom',
frameworkPath: 'node_modules/protractor-cucumber-framework',
specs: [
'features/test.feature'
],
jasmineNodeOpts: {
showColors: true
},
cucumberOpts: {
require: 'features/step_definitions/test.e2e.js',
format: 'pretty' // or summary
}
};
And very simple feature file:
// features/test.feature
Feature: Running Cucumber with Protractor
As a user of Protractor
I should be able to use Cucumber
In order to run my E2E tests
Scenario: Protractor and Cucumber Test
Given I go to "https://angularjs.org/"
When I add "Be Awesome" in the task field
And I click the add button
Then I should see my new task in the list
And the step definition to go with it:
// features/step_definitions/test.e2e.js
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
module.exports = function() {
this.Given('I go to {stringInDoubleQuotes}', function(site) {
browser.get(site);
});
this.When('I add {stringInDoubleQuotes} in the task field', function(task) {
element(by.model('todoList.todoText')).sendKeys(task);
});
this.When('I click the add button', function() {
var el = element(by.css('[value="add"]'));
el.click();
});
this.Then('I should see my new task in the list', function(callback) {
var todoList = element.all(by.repeater('todo in todoList.todos'));
expect(todoList.count()).to.eventually.equal(3);
expect(todoList.get(2).getText()).to.eventually.equal('Do not Be Awesome')
.and.notify(callback);
});
};
I then run protractor protractor.conf.js from the terminal and I only get the feature files displayed without the step definitions running for validation.
(node:8513) DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
[11:35:47] I/launcher - Running 1 instances of WebDriver
[11:35:47] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
Feature: Running Cucumber with Protractor
As a user of Protractor
I should be able to use Cucumber
In order to run my E2E tests
Scenario: Protractor and Cucumber Test
? Given I go to "https://angularjs.org/"
? When I add "Be Awesome" in the task field
? And I click the add button
? Then I should see my new task in the list
Warnings:
1) Scenario: Protractor and Cucumber Test - features/test.feature:6
Step: Given I go to "https://angularjs.org/" - features/test.feature:7
Message:
Undefined. Implement with the following snippet:
Given('I go to {stringInDoubleQuotes}', function (stringInDoubleQuotes, callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
2) Scenario: Protractor and Cucumber Test - features/test.feature:6
Step: When I add "Be Awesome" in the task field - features/test.feature:8
Message:
Undefined. Implement with the following snippet:
When('I add {stringInDoubleQuotes} in the task field', function (stringInDoubleQuotes, callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
3) Scenario: Protractor and Cucumber Test - features/test.feature:6
Step: And I click the add button - features/test.feature:9
Message:
Undefined. Implement with the following snippet:
When('I click the add button', function (callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
4) Scenario: Protractor and Cucumber Test - features/test.feature:6
Step: Then I should see my new task in the list - features/test.feature:10
Message:
Undefined. Implement with the following snippet:
Then('I should see my new task in the list', function (callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
1 scenario (1 undefined)
4 steps (4 undefined)
0m00.000s
[11:35:48] I/launcher - 0 instance(s) of WebDriver still running
[11:35:48] I/launcher - chrome #01 passed
| |
doc_23530932
|
How can I process the html to accomplish this?
I'd prefer a server-side solution, but am not aware of any clean way to pre-process rendered templates in django. So, I assume the most straightforward way to do this is probably a javascript/jquery solution: a script that runs when each page loads, which adds the target="_blank" attribute to all external links but not internal links. But I'm not sure how to do this, either.
A: Try something like
for (var links = document.links, i = 0, a; a = links[i]; i++) {
if (a.host !== location.host) {
a.target = '_blank';
}
}
Don't forget to run the script by the time all links exist in the document tree - in window.onload event.
A: I've been using the following for awhile. Can't remember where I found it originally:
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/)
&& (obj.hostname != location.hostname)
&& !obj.href.match(/^javascript\:/)
&& !obj.href.match(/^$/)
};
That adds an :external jQuery selector, so then you can just do:
$('a:external').attr('target', '_blank');
The nice part about using the custom selector, is that if you need to modify what contitutes an "external" link, you can change it in one place and not worry about the rest of your code. For instance in my organization, we have certain subdomains that aren't "external", but that we still want to open in new windows.
A: You could do something like this:
$(document.body).on('mouseover', 'a[target!=_blank]:not(.local)', function (evt) {
var a = $(this);
var href = a.attr('href');
var domain = href.match(/^https?:\/\/([^:\/]+)/);
if (domain && domain[1] && domain[1] !== "yourdomain.com") {
a.attr('target', '_blank');
} else {
a.addClass('local');
}
});
This will process each link as you click it, and shouldn't process each link more than once. If it needs to be external, the target will be set to _blank and it should open in a new window. Here's a working jsfiddle.
Update: My method of determining if the link stays on-site or not is quite crude. The method in this answer is more thorough. I would probably replace my simple regex match with that test instead.
A: I recommend you do that server side.
Modify the template of the page depending on the locality of the link.
A: As the great accepted answer from @Chris Pratt does not work for e.g. tel: links and other special cases I just use the following variant in order to not touch special links:
(function($) {
$.expr[':'].external = function(obj){
return (obj.hostname != location.hostname) && obj.href.startsWith("http");
};
$('a:external').attr('target', '_blank');
}) (jQuery);
A: You could also do this:
$("a[href^='http://']").attr("target","_blank");
or
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});
A: Slight change in code, which doesn't give errors, additional = in !==
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/) && (obj.hostname !== location.hostname) && !obj.href.match(/^javascript\:/) && !obj.href.match(/^$/);
};
$('a:external').attr('target', '_blank');
A: Another JavaScript solution:
(() => {
(document.querySelectorAll('a')).forEach(link => {
link.hostname !== location.hostname && link.setAttribute('target', '_blank');
})
})();
| |
doc_23530933
|
I know it is possible to get an iOS app as a standalone app using iOS Simulator.
https://github.com/stepanhruda/ios-simulator-app-installer
Our goal: Create a mac app with a text editor which displays the result in an iOS Simulator.
A: No, this is not possible without a lot of reverse engineering on your part of things that I guarantee will likely change in subsequent releases.
You're probably better off trying to hack up an OSX WebKit.framework to behave the way you want and embed a web view from that.
| |
doc_23530934
|
import scrapy
class TwitchSpider(scrapy.Spider):
name = "clips"
def start_requests(self):
urls = [
f'https://www.twitch.tv/wilbursoot/clips?filter=clips&range=7d'
]
def parse(self, response):
for clip in response.css('.tw-tower'):
yield {
'title': clip.css('::text').get()
}
But the key aspect is that I want to call this spider as a function, in another file, instead of using scrapy crawl quotes in the console. Where can I read more on this, or whether this is possible at all? I checked through the Scrapy documentation, but I didn't find much
A: Run the spider from main.py:
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
if __name__ == "__main__":
spider = 'TwitchSpider'
settings = get_project_settings()
# change/update settings:
settings['USER_AGENT'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
process = CrawlerProcess(settings)
process.crawl(spider)
process.start()
Run scrapy from a script.
A: Put your other file in the same directory as your spider file. Then import the spider file like
import spider
Then you will have access to the spider file and can make a spider object.
spi = spider()
Then can call functions on that object such as
spi.parse()
This article shows you how to import other python files classes and functions https://csatlas.com/python-import-file-module/
| |
doc_23530935
|
hindi <- read.table('hindi_text.txt')
hindi
1 कà¥à¤¯à¤¾ बोल रहे हो तà¥à¤®
Then I typed this. It still does not work.
> Sys.setlocale(category="LC_ALL", locale="hindi")
> [1] "LC_COLLATE=Hindi_India.1252;LC_CTYPE=Hindi_India.1252;LC_MONETARY=Hindi_India.1252;LC_NUMERIC=C;LC_TIME=Hindi_India.1252"
> hindi
> 1 कà¥à¤¯à¤¾ बोल रहे हो तà¥à¤®
I tried this with reading Chinese characters by changing the locale to Chinese and it worked.
> chinese <- read.table("chinese.txt")
> Sys.setlocale(category="LC_ALL", locale="chinese")
> [1] "LC_COLLATE=Chinese (Simplified)_China.936;LC_CTYPE=Chinese (Simplified)_China.936;LC_MONETARY=Chinese (Simplified)_China.936;LC_NUMERIC=C;LC_TIME=Chinese (Simplified)_China.936"
> chinese
> 1 锘夸负浠€涔堣繖涓敞鎰忥紝杩欎釜宸ヤ綔
Why does this work with Chinese and not Hindi (and some other languages too) and is there any way I can make it work?
| |
doc_23530936
|
Please,help 3 days wasted :(
| |
doc_23530937
|
dag = DAG(
'MY_DAG',
default_args=args,
schedule_interval='0 1,6 * * *',
max_active_runs=1,
catchup=False)
For this:
dag = DAG(
'MY_DAG',
default_args=args,
schedule_interval='30 1,6 * * *',
max_active_runs=1,
catchup=False)
After this change, DAG got triggered right after. Is there something I can do to avoid this?
Thank you very much!
| |
doc_23530938
|
But it doesn't work with ng-dropdown-multiselect texts.
I tried to associate translation-texts with $scope variables and apply $scope.$watch to wait changes, but it not worked too.
Someone knows how make it multi-language?
<div
ng-dropdown-multiselect=""
options="myModelOptions"
selected-model="mySelectedItem"
extra-settings="mySettings"
translation-texts="{
'checkAll': myScopeVariable.selectAll,
'uncheckAll': myScopeVariable.selectNone,
'buttonDefaultText': myScopeVariable.selectZero,
'selectionCount': myScopeVariable.selectCount,
'dynamicButtonTextSuffix': myScopeVariable.selectSufix
}">
</div>
A: You don't need to watch a scope, the translation-texts attributes they provided works only during building the dom.
You can use a trick by rebuilding the select for everytime you change a language.
1- Adding condition for displaying the select, for this example ng-if="!unready".
And use the translate filter directly.
<div ng-if="!unready" ng-dropdown-multiselect="" options="cars" selected-model="selectedCar" extra-settings="mySettings" translation-texts="{
'checkAll': ('selectAll' | translate),
'uncheckAll': ('selectNone' | translate),
'buttonDefaultText': ('selectZero' | translate),
'selectionCount': ('selectCount' | translate),
'dynamicButtonTextSuffix': ('selectSufix' | translate)
}">
</div>
2- catch the language change detection if the button changing it is not in the same controller, and set the variable to not display the select, adding a little timeout to display it again so the select will be re-rendered.
$rootScope.$on('$translateChangeSuccess', function(event, current, previous) {
// Language has changed
$scope.unready = true;
$timeout(function() {
$scope.unready = false;
}, 10);
});
A working plunker https://embed.plnkr.co/2psHUD/
| |
doc_23530939
|
RoomAvailability Controller in Php
public function storeRoomAvailability()
{
$roomId = request();
$test = RoomAvailability::where('room_id', $roomId->room_id)->get();
if (is_null($test)) {
return response()->json([
'success' => false,
'message' => 'The room is already taken'
]);
} else {
$roomAvailability = RoomAvailability::create([$this->validateRequest()]);
return response()->json([
'success' => true,
'message' => 'Room Availability has been created successfully.',
'data' => $roomAvailability
]);
}
}
private function validateRequest()
{
return request()->validate([
'room_id' => 'required |unique:room_availabilities',
'reservation_id' => 'nullable',
'booking_id' => 'required',
'check_in_date' => 'required',
'check_out_date' => 'required'
]);
}
Parameters from Angular 8
[
{
"reservation_id": 25,
"room_id": 1,
"check_in_date": "2020-04-27 12:00:00",
"check_out_date": "2020-04-30 12:00:00",
"availability": false,
"status": "booked",
"booking_id": 26
},
{
"reservation_id": 26,
"room_id": 2,
"check_in_date": "2020-04-27 12:00:00",
"check_out_date": "2020-04-30 12:00:00",
"availability": false,
"status": "booked",
"booking_id": 26
}
]
A: first convert the parameters that comes from angular to associative arrays
$arrayValues=json_decode($Parameters_from_Angular,true);
then, insert the new values using bulk insert:
RoomAvailability::insert($arrayValues);
| |
doc_23530940
|
class singelton
{
public:
static singelton* Instance()
{
if (m_pInstance == 0)
{
m_pInstance = new singelton();
}
return m_pInstance;
}
void setData(std::string input) { data = input; }
void getData() const { std::cout << data << std::endl; }
private:
singelton() {}
~singelton() {}
static singelton* m_pInstance;
std::string data;
};
typedef singelton s;
//what is this? Why need a singleton name? I mean "singelton*".
singelton* singelton::m_pInstance = 0;
int main(int argc, char** argv)
{
s.Instance()->setData("Something...");
s.Instance()->getData();
return 0;
}
What is singelton* singelton::m_pInstance = 0;?
This function assigns zero/null to a singleton instance, but why need use singleton* ? That assignment like a function, but use as assignment.
A: Static data members are not part of objects of a given class type; they are separate objects. As a result, the declaration of a static data member is not considered a definition. So static member must be defined outside of the class declaration.
In your example:
*
*singelton * is a type of member.
*singleton:: is class name (like namespace)
*and m_pInstance is member name
P.S.: Because of static variables are initialised with 0 by default in C++, you don't need to explicitly set m_pInstance to 0 (or NULL). The definition only will be enough:
singelton * singelton::m_pInstance;
A:
What is singelton* singelton::m_pInstance = 0;?
It's the initialiser for the static member variable m_pInstance, statically initialising the pointer to be null. singelton* (pointer to singelton) is the type of the variable; singlelton::m_pInstance is the (qualified) name of the variable; and = 0 is the initialiser.
This function assigns zero/null to a singleton instance, but why need use singleton* ?
No, it initialises the pointer to null; it doesn't point to anything yet. The object itself will be created, and the pointer updated to point to it, the first time someone calls Instance(). It's a pointer so that the object itself can be created when it's first needed, rather than at some arbitrary point during program startup - this is known as "lazy initialisation".
Beware that, in C++, there is no way to implement the Singleton anti-pattern correctly. This particular implementation has the problems of leaking the object, and not being thread-safe. I strongly recommend that you get rid of it: just instantiate the object in an appropriate place, with a lifetime that's longer than whatever uses it, and pass references to whatever needs it.
A: Use
Singleton::Instance()->setData("Hello");
and
Singleton::Instance()->getData();
The class can only have one instance - hence called singleton
And the Singleton::Instance gives you access to that
singelton* singelton::m_pInstance = 0;
Initializes it and when you first use it the singleton is created
| |
doc_23530941
|
Technology: Android
A: You have 2 options:
1. subclass Transformation and implement your crop logic
2. subclass one of the transformations you've mentioned and apply your logic
| |
doc_23530942
|
They almost the same, but have some differences in their paths, which not allow me to combine them into one because of hell in openapi docs.
I've tried to create a common module and separate different methods by adding multilevel decorators, like
@ROUTER.get("/route-a/", tags=["RouteA"])
@ROUTER.get("/route-b/", tags=["RouteB"])
async def my_func():
pass
This solution makes openapi docs worse, it's not splitting 2 methods by tags in openapi, but put both /route_a and /route_b in both tags RouteA and RouteB.
Is it possible to do somehow, without separating them in different modules/routers?
| |
doc_23530943
|
I am running a dataflow task in which I am extracting data from a source. I wanted to know the size (kb or mb) of data extract.
I do not want to use script component, because its going to slow the etl process.
| |
doc_23530944
|
[{"2018-06-19":{"charge":55000,"xcharge":15000}},
{"2018-06-20":{"charge":55000,"xcharge":15000}},
{"2018-06-21":{"charge":55000,"xcharge":15000}},
{"2018-06-22":{"charge":55000,"xcharge":15000}},
{"2018-06-23":{"charge":55000,"xcharge":15000}},
{"2018-06-24":{"charge":55000,"xcharge":15000}}]
My hidden input and Button
<input type="hidden" name="chargeArray" id="chargeArray" value='[{"2018-06-19":{"charge":55000,"xcharge":15000}},{"2018-06-20":{"charge":55000,"xcharge":15000}},{"2018-06-21":{"charge":55000,"xcharge":15000}},{"2018-06-22":{"charge":55000,"xcharge":15000}},{"2018-06-23":{"charge":55000,"xcharge":15000}},{"2018-06-24":{"charge":55000,"xcharge":15000}}]' />
<button class="btn btn-default" type="button" onclick="change_room_charge();"><span class="glyphicon glyphicon-edit"></span></button>
I have tried it with this, but it is failing. charge value is not changing to new value.
function change_room_charge(){
var chargeArray = JSON.parse($('#chargeArray').val());
$.each(chargeArray, function (index, item) {
item[0].charge = item[0].charge.replace(666);
});
$('#chargeArray').val(JSON.stringify(chargeArray));
}
What i want is to change all existing charge values in hidden input to new value.
A: Whatever you are doing is very strange, but I'm going with it. You have your objects keyed by a date so you need to go get that key first. So in the code below, I get the key by finding all the keys for the item and taking the first one. From there you can set the value to whatever you want and then put it back into the input.
function change_room_charge() {
var chargeArray = JSON.parse($('#chargeArray').val());
$.each(chargeArray, function(index, item) {
var key = Object.keys(item)[0];
item[key].charge = 666;
});
$('#chargeArray').val(JSON.stringify(chargeArray));
console.log($('#chargeArray').val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="chargeArray" id="chargeArray" value='[{"2018-06-19":{"charge":55000,"xcharge":15000}},{"2018-06-20":{"charge":55000,"xcharge":15000}},{"2018-06-21":{"charge":55000,"xcharge":15000}},{"2018-06-22":{"charge":55000,"xcharge":15000}},{"2018-06-23":{"charge":55000,"xcharge":15000}},{"2018-06-24":{"charge":55000,"xcharge":15000}}]' />
<button class="btn btn-default" type="button" onclick="change_room_charge();">
<span class="glyphicon glyphicon-edit"></span>
</button>
| |
doc_23530945
|
*
*example.com/us/en/hello (en_US)
*example.com/be/fr/bonjour (fr_BE)
Is there any way to do this using config? If not, where is the best place to start customizing?
A: It doesn't look it's possible to do through config, but it can be done by replacing default implementation of PatternGenerationStrategyInterface by your own implementation.
You can check out default implementation that bundle uses here.
After you create your own implementation, just make bundle use your own implementation by setting the config parameter. If you're using YAML for example:
parameters:
jms_i18n_routing.pattern_generation_strategy.class: YourBundle\YourImplementationClass
Hint: you can basically copy/paste from default implementation and change line 69 to use str_replace('_', '/', $locale) instead of just $locale. That way, newly generated route pattern will contain a / if locale contains an _.
Not very elegant solution, but bundle unfortunately doesn't provide enough configuration to make it prettier.
| |
doc_23530946
|
<!--- Query the DataBase --->
<cfparam name="url.colors" default="">
<cfif structKeyExists(form, "colordb")>
<cfset url.colordb = form.colordb>
</cfif>
<cfquery datasource="bentest" name="colors">
SELECT *
FROM color_codes
<cfif structKeyExists(url,"colordb") and isNumeric(url.colordb)>
WHERE id=#url.colordb#
</cfif>
</cfquery>
<!--- Add Selector for user to select a color --->
<div class="selector">
<cfoutput>
<form action="?contentId=colorPickdb" name="clr" method="post" class="clr">
<select class="clr" name="colordb" onChange="submit();">
<option selected>Select A Color!</option>
<cfloop query="colors">
<option value="#colors.id#">#colors.color#</option>
</cfloop>
</select>
</form>
</cfoutput>
</div>
<div class="dump">
<!--- Output results of Query --->
<p><cfif structKeyExists(form, "colordb")>
<cfoutput query="colors">
#colors.color# <br>
#colors.hexvalue# <br><br>
</cfoutput>
</cfif>
<br>
</p>
</div>
A: You can use query of query here.
<!--- Query the DataBase --->
<cfparam name="url.colors" default="">
<cfquery datasource="bentest" name="colors">
SELECT *
FROM color_codes
</cfquery>
<!--- Add Selector for user to select a color --->
<div class="selector">
<cfoutput>
<form action="?contentId=colorPickdb" name="clr" method="post" class="clr">
<select class="clr" name="colordb" onChange="submit();">
<option selected>Select A Color!</option>
<cfloop query="colors">
<option value="#colors.id#">#colors.color#</option>
</cfloop>
</select>
</form>
</cfoutput>
</div>
<div class="dump">
<!--- Output results of Query --->
<p>
<cfif structKeyExists(form, "colordb")>
<cfquery dbtype="query" name="colorSelected">
SELECT *
FROM colors
WHERE id=#form.colordb#
</cfquery>
<cfoutput query="colorSelected">
#colorSelected.color# <br>
#colorSelected.hexvalue# <br><br>
</cfoutput>
</cfif>
<br>
</p>
</div>
| |
doc_23530947
|
ReactContextBaseJavaModule
But my needs are different. I need to execute a function on my component. I was trying to expose function by @ReactNative annotation in my class that extends:
ViewGroupManager
but this function is not visible for react at all. Is there any possibility to get access to the ViewGroupManager object from ReactContextBaseJavaModule object? If not than what is the most convenient way to expose function from native component to ReactNative?
here is my ReactContextBaseJavaModule implementation:
public class VidyoModule extends ReactContextBaseJavaModule {
public VidyoModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "RNTVideoManager";
}
@ReactMethod
public void showToast(){
Toast.makeText(getCurrentActivity(), "Test", Toast.LENGTH_SHORT).show();
}
@ReactMethod
public void connectToRoom(){
}
}
I am able to execute both showToast and connectToRoom functions from react.
Here is an implementation of ViewGroupManager:
public class VidyoComponentManager extends ViewGroupManager<VidyoView> {
private static final String COMPONENT_NAME = "RNTVideo";
public VidyoComponentManager(){
}
@Override
public String getName() {
return COMPONENT_NAME;
}
@Override
protected VidyoView createViewInstance(ThemedReactContext reactContext) {
return new VidyoView(reactContext);
}
@ReactMethod
public void connectToRoom(){
}
}
My ReactPackage looks like this:
public class VidyoPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
VidyoModule module = new VidyoModule(reactContext);
modules.add(module);
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.<ViewManager>singletonList(
new VidyoComponentManager()
);
}
}
and in this case function connectToRoom is not visible for ReactNative. What shouldI do here? Should I user commands?
public Map<String, Integer> getCommandsMap() {
return MapBuilder.<String, Integer>builder()
.put("connectToRoom", 1)
.build();
}
A: Solution has been found. To make functions from ViewManager(android side) visible to React Native we need to implement getCommandsMap, than iterate through commands and "registrate" them as available functions on React side
const commands = NativeModules.UIManager.RNTVideo.Commands;
Object.keys(commands).forEach(command => {
NativeModules.RNTVideoManager[command] = (handle, ...rawArgs) => {
const args = rawArgs.map(arg => {
if (typeof arg === 'function') {
callbackMap.set(nextCallbackId, arg);
return nextCallbackId++;
}
return arg;
});
NativeModules.UIManager.dispatchViewManagerCommand(handle, commands[command], args);
};
});
If there is any better solution please tell me about it :)
| |
doc_23530948
|
A: Object detection is a very complex problem that includes some real hardcore math and long tuning of parameters to the computation methods involved. Your best bet is to use some freely available library for that - Google will help.
A: There are lot of algorithms about the theme and no one is the best of all. It's usually a mixture of them what makes the best solution to the solution.
For example, for object movement detection you could look at frame differencing and misture of gaussians.
Also, it's very dependent of your application, the environment (i.e. noise, signal quality), the processing capacity you may have available, the allowable error margin...
Besides, for it to work, most of time it's first necessary to do some kind of image processing to the input data like median filter, sobel filter, contrast enhancement and a large so on.
I think you should start reading all you can: books, google and, very important, a lot of papers about the subjects (there are many free in internet) you are interested in.
And first of all, i think it's fundamental (at least it has been for me) having a good library for testing. The one i have used/use is OpenCV. It's very complete, implement many of the actual more advanced algorithms, is very active, has a big community and it's free.
Open Computer Vision Library (OpenCV)
Have luck ;)
A: Take a look at AForge.NET. It's nowhere near Project Natal's levels of accuracy or usefulness, but it does give you the tools to learn the algorithms easily. It's an image processing and AI library and there are several tutorials on colored object tracking and motion detection.
Another one to look at is OpenCV from Intel. I believe it's a bit more advanced, but it's written in C.
A: Take a look at this. It might get you started in this complex field. The algorithm pages that it links to are interesting reading.
http://sun-valley.stanford.edu/projects/helicopters/final.html
A: This lecture by Jeff Hawkins, will give you an idea about the state of the art in this super-difficult field.
Seems that video disappeared... but this vid should cover similar ground.
| |
doc_23530949
|
# -*- coding: utf-8 -*-
import codecs
import unicodecsv
raw_contents = 'He observes an “Oversized Gorilla” near Ashford'
encoded_contents = unicode(raw_contents, errors='replace')
with codecs.open('test.csv', 'w', 'UTF-8') as f:
w = unicodecsv.writer(f, encoding='UTF-8')
w.writerow(["1", encoded_contents])
This is the traceback:
Traceback (most recent call last):
File "unicode_test.py", line 11, in <module>
w.writerow(["1", encoded_contents])
File "/Library/Python/2.7/site-packages/unicodecsv/__init__.py", line 83, in writerow
self.writer.writerow(_stringify_list(row, self.encoding, self.encoding_errors))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py", line 691, in write
return self.writer.write(data)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 17: ordinal not in range(128)
I thought converting it to Unicode would be good enough, but that doesn't seem to be the case. I'd really like to understand what is happening so that I'm better prepared to handle these errors in other projects in the future.
From the traceback, it looks like I can reproduce the error like this:
>>> raw_contents = 'He observes an “Oversized Gorilla” near Ashford'
>>> raw_contents.encode('UTF-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 15: ordinal not in range(128)
>>>
Up until now, I thought I had a decent working knowledge of working with Unicode text in Python 2.x, but this has humbled me.
A: You should not use codecs.open() for your file. unicodecsv wraps the csv module, which always writes a byte string to the open file object. In order to write that byte string to a Unicode-aware file object such as returned by codecs.open(), it is implicitly decoded; this is where your UnicodeDecodeError exception stems from.
Use a file in binary mode instead:
with open('test.csv', 'wb') as f:
w = unicodecsv.writer(f, encoding='UTF-8')
w.writerow(["1", encoded_contents])
The binary mode is not strictly necessary unless your data contains embedded newlines, but the csv module wants to control how newlines are written to ensure that such values are handled correctly. However, not using codecs.open() is an absolute requirement.
The same thing happens when you call .encode() on a byte string; you already have encoded data there, so Python implicitly decodes to get a Unicode value to encode.
| |
doc_23530950
|
How can I compare my user(left) image to the computer(right) generated image? So that I can put on a JLabel in the middle stating whether "You Win!" or "You Lose!" or "DRAW!"?
Here's my code I'm trying to figuring out how to enable my comparison of the image:
btrock.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
user.setIcon(new ImageIcon("ROCK LEFT.PNG"));
int index = (int) (Math.random() * (images.length - 0));
computer.setIcon(new ImageIcon(images[index]));
String blah = new Integer(index).toString();
if(user.getIcon() == computer.getIcon(images[index])){
lbl1.setText("DRAW!");
}
}
});
A: for beginners you could map your Images with an according enum. then you can easily compare the values of the gesture instead of comparing images.
enum Gesture {ROCK, SCISSOR; PAPER}
Map<Gesture, ImageIcon> leftImages;
Map<Gesture, ImageIcon> rightImages;
Gesture rightGesture;
Gesture leftGesture;
void setLeftGesture(Gesture gesture) {
leftGesture = gesture;
setLeftImage(leftImages.get(gesture);
}
//TODO
void setRightGesture(...);
boolean isEqualGesture(){
return rightGesture == leftGesture;
}
boolean leftWins(){
return rightGesture == Gesture.ROCK && leftGesture == Gesture.PAPER;
}
//TODO
boolean rightWins(){...}
so whenever you set your gesture left or right you simply call these code snippets above.
public void actionPerformed(ActionEvent e) {
//let's assume we are on rocks:
setLeft(Gesture.ROCK);
setRight(randomGesture());
if(isEqualGesture()) {
//write "draw" in your text box
}else if(leftWins()){
//player did win, write a notification
}else if(rightWins()){
//computer did win
}
}
possible implementations
create a map:
Map<Gesture, ImageIcon> rightImages = new HashMap<>();
ImageIcon rightRock = new ImageIcon...//i don't know that part of your implementations
ImageIcon rightScissor = ...
ImageIcon rightPaper = ...
rightImages.put(Gesture.ROCK, rightRock);
rightImages.put(Gesture.SCISSOR, rightScissor);
rightImages.put(Gesture.PAPER, rightPaper);
the same applies for the left images. The setting up of the map should happen in the very beginning of your app. Doing so has the effect, that you load the images ONLY ONCE and can re-use them again and again. Best practice would be to create a init() methode, where you do all the setup stuff...
| |
doc_23530951
|
CONECTION_REFUSED="Connection refused"
OUTPUT=$(ffmpeg -i rtsp://192.168.1.46:8080/h264_ulaw.sdp -vcodec copy output.mp4 -loglevel 16 -report 2>&1)
if [[ "$OUTPUT" == *"$CONECTION_REFUSED"* ]]; then
echo "It's there."
fi
echo $?
In order to test several crashes, if the script starts without RTSP server up, FFmpeg fails with an error that says "Connection refused", but if I run the command with the RTSP server up and down after running, FFmpeg only stops without notifying any kind of error.
Is there any way to catch the lost-connection error?
Thanks
| |
doc_23530952
|
x { Error: Command failed: heroku plugins:install heroku-cli-deploy
Installing plugin heroku-cli-deploy... !
! yarn --non-interactive
! --mutex=file:C:\Users\hassnan.ali\AppData\Local\heroku\yarn
! --cache-folder=C:\Users\hassnan.ali\AppData\Local\heroku\yarn exited with
! code 1
! warning There appears to be trouble with your network connection.
! Retrying...
! warning There appears to be trouble with your network connection.
! Retrying...
! warning There appears to be trouble with your network connection.
! Retrying...
! warning There appears to be trouble with your network connection.
! Retrying...
! error An unexpected error occurred:
! "http://cli-npm.heroku.com/heroku-cli-deploy/-/heroku-cli-deploy-0.4.0/d9f2343c51c08107f6265b34e138c6ba07128f10.tgz:
! ESOCKETTIMEDOUT".
!
at ChildProcess.exithandler (child_process.js:271:12)
at emitTwo (events.js:125:13)
at ChildProcess.emit (events.js:213:7)
at maybeClose (internal/child_process.js:927:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
killed: false,
code: 1,
signal: null,
cmd: 'heroku plugins:install heroku-cli-deploy' }
Execution complete
What I've done so far?
*
*installed Heroku toolbelt [success]
*created herkou free account [success]
*logged in to my heroku account [success]
*run 'jhipster heroku' command [failed] [error is stated above]
I'm on windows 7 64bit. jhipster 4.9.0
I've generated my app separately using jhipster server command etc.
please note: my internet is working just fine.
Any kind of help or suggestion is appreciated. I'm stuck please help. I've never used heroku before.
| |
doc_23530953
|
I can send the date from curl like this:
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST https://ictexpo.herokuapp.com/users -d "{\"user\":{\"name\":\"Choity\"}}"
But when I want to send the same data from java I don't get the outcome.
String urlParameters = "{\"user\" : {\"name\" : \"lssl\" }}";
URL url2 = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) url2.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Can anyone please tell me why I'm getting exceptopn?
| |
doc_23530954
|
2018-09-16 04:11:47 W3SVC10 webserver 107.6.166.194 POST /api/uploadjsontrip - 443 - 203.77.177.176 HTTP/1.1 Java/1.8.0_45 - - vehicletrack.biz 200 0 0 506 872 508
Data Description:
date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-substatus sc-win32-status sc-bytes cs-bytes time-taken
How to write the Grok pattern to extract the value of each column??
I tried following but it did not work.
%{TIMESTAMP_ISO8601:timestamp} %{NOTSPACE:s-sitename} %{WORD:cs-method} %{URIPATH:cs-uri-stem} %{NOTSPACE:cs-uri-query} %{NUMBER:s-port} %{NOTSPACE:cs-username} %{IPORHOST:c-ip} %{NOTSPACE:cs(User-Agent)} %{NOTSPACE:cs(Cookie)} %{NOTSPACE:cs(Referer)} %{NOTSPACE:cs-host} %{NUMBER:sc-status:int} %{NUMBER:sc-substatus:int} %{NUMBER:sc-win32-status:int} %{NUMBER:sc-bytes:int} %{NUMBER:cs-bytes:int} %{NUMBER:time-taken:int}" ,
"message", "%{TIMESTAMP_ISO8601:timestamp} %{IPORHOST:s-sitename} %{WORD:cs-method} %{URIPATH:cs-uri-stem} %{NOTSPACE:cs-uri-query} %{NUMBER:s-port} %{NOTSPACE:cs-username} %{IPORHOST:c-ip} %{NOTSPACE:cs(User-Agent)} %{NOTSPACE:cs(Referer)} %{NUMBER:response:int} %{NUMBER:sc-substatus:int} %{NUMBER:sc-substatus:int} %{NUMBER:time-taken:int}" ,
"message", "%{TIMESTAMP_ISO8601:timestamp} %{WORD:cs-method} %{URIPATH:cs-uri-stem} %{NOTSPACE:cs-post-data} %{NUMBER:s-port} %{IPORHOST:c-ip} HTTP/%{NUMBER:c-http-version} %{NOTSPACE:cs(User-Agent)} %{NOTSPACE:cs(Cookie)} %{NOTSPACE:cs(Referer)} %{NOTSPACE:cs-host} %{NUMBER:sc-status:int} %{NUMBER:sc-bytes:int} %{NUMBER:cs-bytes:int} %{NUMBER:time-taken:int}
Please help me.
Thanks in advance.
A: This will work for grok line that you have provided. But it may fail near user-agent and cookie depending on data.
%{TIMESTAMP_ISO8601:timestamp} %{NOTSPACE:s_sitename} %{WORD:s_computername} %{IPV4:s_ip} %{WORD:cs_method} %{URIPATH:cs_uri_stem} %{DATA:cs_uri_query} %{NUMBER:s_port} - %{IPV4:cs_ip} HTTP/%{NUMBER:cs_vserion} %{NOTSPACE:cs_user_agent} %{NOTSPACE:cs_cookie} (-|%{URI:cs_refrer}) %{IPORHOST:cs_host} %{INT:sc_status} %{INT:sc_substatus} %{INT:sc_win32-status} %{INT:sc_bytes} %{INT:cs_bytes} %{INT:time_taken}
Also, you might find this tool easier to do any grok testing and debugging https://grokdebug.herokuapp.com/
| |
doc_23530955
|
The image Nested FSM Example provides a simple scenario. Here the Parent FSM is in the running state, this has a child FSM which is in the top state. This state itself has a child FSM which has either the off or on state. I would like to suppress or ignore all transitions on the first child and parent FSMs, in this case 'down' transition on first child and 'stop' on the parent, when child two is in the 'on' state. You could imagine in a more complex scenario there could be a considerable number of transitions on the parent or child state.
Any ideas of a good way to achieve this?
Thanks in advance,
A: In my experience, it's a good practise to think of transitions (or better trigger) as events that should be handled depdending on their current state. For instance, when your machine is in the init state, the event stopping will not be handled and -- depending on your configuration -- may even raise an exception.
So rather than 'supressing' transitions, one could rephrase your use case to 'my machine should handle events stop and down differently when in state running_top_on'.
Pytransitions evaluates potential transitions in the following order:
*
*Transitions defined in children will be evaluated before transitions defined in parents
*Transitions in a state are evaluated in the order they were added
*Transitions will only be conducted when all conditions return True and all unless callbacks return False
Strategy one: Handle down/stop events in running_top to override handling strategies in parents.
You could for instance add internal transitions that basically do nothing:
state_config = {
'name': 'top',
'children': ['on', 'off'],
'initial': 'off',
'transitions': [['begin', 'off', 'on'],
['end', 'on', 'off'],
['down', 'on', None],
['stop', 'on', None]]
}
However, you might want to add a callback to the transitions to log events when your machine was instructed to stop even though its in a critical state.
Strategy two: Introduce unless in your transitions.
transitions = [ # ...,
{'trigger': 'stop', 'source': 'running', 'dest': 'stopping', 'unless': 'is_running_top_on'}
Quite conventiently, we do not have to write custom condition callbacks in this case since our model has already been decorated with state check functionality.
Strategy 3: Add transitions that handle special cases BEFORE generic transitions.
transitions = [['start', 'init', 'running'],
['stop', 'running_top_on', None],
['stop', 'running', 'stopping']]
The graph will look like the first graph BUT the transition will actually be defined on the root level which means that it will be evaluated ONLY when the event has not been handled by a child state. This means if we add ['bottom', 'running_top_up', Nome] here, it will not be called when bottom handling has been defined in the running state as ['bottom', 'top', 'down'].
| |
doc_23530956
|
=IF(A2="Male","M","F")
I have coded it as below to show the value in the 5th column ('F') offset of 'A'
Sub Gender1()
'
' Gender1 Macro
'
' =IF(A2="Male","M","F")
Dim rCell As Range
Dim rRng As Range
Set rRng = Range("A2", Range("A2").End(xlDown))
For Each rCell In rRng.Cells
If rCell.Value = "Male" Then
result = "M"
rCell.Offset(0, 5).Select
ActiveCell.Value = result
ElseIf rCell.Value = "Female" Then
result = "F"
rCell.Offset(0, 5).Select
ActiveCell.Value = result
Else
result = "NULL"
rCell.Offset(0, 5).Select
ActiveCell.Value = result
End If
Next rCell
End Sub
I wanted to understand if the method is correct and should offset be used to display value or is there a better way to optimize the code and display value in the desired column.
I have to loop through 100 000 rows
A: If you are dealing with 1 lac rows, I would suggest you to adopt another approach.
Read the column A data into an Array and construct another Array based on your IF condition and write the resultant array at once onto the Sheet.
Since looping over 100 thousand rows will take time if you interact with the cells but the Array approach will take maybe less than a second.
Give this a try to see the difference...
The below code took less than a second when I ran this code on 150000 rows of data.
Sub Gender()
Dim lr As Long, i As Long
Dim x, y()
lr = Cells(Rows.Count, 1).End(xlUp).Row
x = Range("A2:A" & lr).Value
ReDim y(1 To UBound(x, 1), 1 To 1)
For i = 1 To UBound(x, 1)
If x(i, 1) = "Male" Then
y(i, 1) = "M"
ElseIf x(i, 1) = "Female" Then
y(i, 1) = "F"
Else
y(i, 1) = "NULL"
End If
Next i
Range("F2").Resize(UBound(y), 1).Value = y
End Sub
A: To mimic the original function =IF(A2="Male","M","F") the following code works:
Sub mimicIf()
Dim r As Range
Dim cell As Range
Set r = Range("A2")
Set r = Range(r, r.End(xlDown))
For Each cell In r
If cell = "Male" Then
cell.Offset(0, 5) = "M"
Else
cell.Offset(0, 5) = "F"
End If
Next cell
End Sub
However, your code is actually for the function =IF(A2="Male","M",IF(A2="Female","F","Null"))
As BruceWayne commented, you should avoid .Select and ActiveCell, unless really needed. As far as using .offset(), it's quite efficient, assuming you are using ranges. If you really need efficiency, however, doing manipulations in code using arrays/variants is often the answer.
| |
doc_23530957
|
If so, please, follow these instructions: https://github.com/microsoft/vscode-react-native#customization (error code 604) (error code 303)
how I can resolve this????
| |
doc_23530958
|
no such table: background_task
here are my INSTALLED_APPS:
INSTALLED_APPS = [
'appname.apps.AppnameConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'background_task',
]
I also tried python manage.py makemigrations background_task before python manage.py makemigrations but this also failed.
My workaround for now is to rename the tasks.py to tasks and to comment the part in the urls.py where I call the tasks from the tasks.py and deleting background_task from settings.py. Then I do all the migrating and then undo my renaming/commenting/deleting.
This works, but there must be a better way?
I already tried the tips from here (but my workaround is based a little bit on OPs own answer) and here.
A: Run the following command.
python manage.py migrate --run-syncdb
Else:
You can delete your migrations (will delete your database) folder and then try recreating them again.
python manage.py makemigrations
python manage.py migrate
python manage.py migrate --run-syncdb
A: You need to follow the steps of documentation in order. If you have already the imports and usages of the background_task in your views, you need to comment them all, perform the python manage.py makemigrations and python manage.py migrate, then uncomment them again.
| |
doc_23530959
|
I looked on Cocoapods Github repo, but there doesn't seem to be a similar issue.
### Stack
```
CocoaPods : 0.33.1
Ruby : ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]
RubyGems : 2.0.14
Host : Mac OS X 10.9.3 (13D65)
Xcode : 5.1.1 (5B1008)
Ruby lib dir : /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib
Repositories : master - https://github.com/CocoaPods/Specs.git @ a9178ca54fa395859f71056e7015fd125fa93495
```
### Podfile
```ruby
platform :ios, '7.0'
pod 'OpenWeatherMapAPI', '~> 0.0.5'
```
### Error
```
RuntimeError - [!] Xcodeproj doesn't know about the following attributes {"name"=>"JSON"} for the 'PBXReferenceProxy' isa.
Please file an issue: https://github.com/CocoaPods/Xcodeproj/issues/new
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:300:in `configure_with_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project.rb:230:in `new_from_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:328:in `object_with_uuid'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:279:in `block (2 levels) in configure_with_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:278:in `each'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:278:in `block in configure_with_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:275:in `each'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:275:in `configure_with_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project.rb:230:in `new_from_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:328:in `object_with_uuid'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:291:in `block (3 levels) in configure_with_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:290:in `each'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:290:in `block (2 levels) in configure_with_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:288:in `each'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:288:in `block in configure_with_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:285:in `each'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project/object.rb:285:in `configure_with_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project.rb:230:in `new_from_plist'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project.rb:175:in `initialize_from_file'
/Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/project.rb:93:in `open'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/installer/analyzer.rb:517:in `block in compute_target_platforms'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/installer/analyzer.rb:514:in `each'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/installer/analyzer.rb:514:in `compute_target_platforms'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/installer/analyzer.rb:55:in `analyze'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/installer.rb:176:in `analyze'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/installer.rb:98:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/user_interface.rb:52:in `section'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/installer.rb:97:in `resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/installer.rb:89:in `install!'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/command/project.rb:40:in `run_install_with_update'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/command/project.rb:70:in `run'
/Library/Ruby/Gems/2.0.0/gems/claide-0.6.1/lib/claide/command.rb:281:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods/command.rb:48:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/bin/pod:33:in `<top (required)>'
/usr/bin/pod:23:in `load'
/usr/bin/pod:23:in `<main>'
```
What should I do?
Thank you for your help!
| |
doc_23530960
|
Looks like Azure doesnt support anonymous read-access to Azure ACR. Hence only way is to push image to docker registry and pull the image form docker registry during container deployment in azure.
Is it possible? If so, how can I use azure template to achieve it? Any example please?
A: I thinks it is possible to create the azure container by using imageRegistryCredentials property, you could refer to the sample template.
{
"name": "string",
"type": "Microsoft.ContainerInstance/containerGroups",
"apiVersion": "2018-04-01",
"location": "string",
"tags": {},
"properties": {
"containers": [
{
"name": "string",
"properties": {
"image": "string",
"command": [
"string"
],
"ports": [
{
"protocol": "string",
"port": "integer"
}
],
"environmentVariables": [
{
"name": "string",
"value": "string"
}
],
"resources": {
"requests": {
"memoryInGB": "number",
"cpu": "number"
},
"limits": {
"memoryInGB": "number",
"cpu": "number"
}
},
"volumeMounts": [
{
"name": "string",
"mountPath": "string",
"readOnly": boolean
}
]
}
}
],
"imageRegistryCredentials": [
{
"server": "string",
"username": "string",
"password": "string"
}
],
"restartPolicy": "string",
"ipAddress": {
"ports": [
{
"protocol": "string",
"port": "integer"
}
],
"type": "Public",
"ip": "string",
"dnsNameLabel": "string"
},
"osType": "string",
"volumes": [
{
"name": "string",
"azureFile": {
"shareName": "string",
"readOnly": boolean,
"storageAccountName": "string",
"storageAccountKey": "string"
},
"emptyDir": {},
"secret": {},
"gitRepo": {
"directory": "string",
"repository": "string",
"revision": "string"
}
}
]
}
}
For more details, you could refer to this link.
If the image is public, the password is not required.
| |
doc_23530961
|
_______________________________________________________________________________________________________ TestAggregateTiltReadings.test_initial_run _______________________________________________________________________________________________________
------------------------------------------------------------------------------------------------------------------ Captured stderr call ------------------------------------------------------------------------------------------------------------------
INFO 2022-02-20 20:57:32,196 services 1 140188905805632 2022-02-20 20:57:32.196975+00:00
INFO 2022-02-20 20:57:32,197 services 1 140188905805632 Aggregating 4 new tilt readings
------------------------------------------------------------------------------------------------------------------- Captured log call --------------------------------------------------------------------------------------------------------------------
INFO brew_dash.tilts.services:services.py:33 2022-02-20 20:57:32.196975+00:00
INFO brew_dash.tilts.services:services.py:34 Aggregating 4 new tilt readings
_______________________________________________________________________________________________________ TestAggregateTiltReadings.test_initial_run _______________________________________________________________________________________________________
------------------------------------------------------------------------------------------------------------------ Captured stderr call ------------------------------------------------------------------------------------------------------------------
INFO 2022-02-20 20:57:32,196 services 1 140188905805632 2022-02-20 20:57:32.196975+00:00
INFO 2022-02-20 20:57:32,197 services 1 140188905805632 Aggregating 4 new tilt readings
------------------------------------------------------------------------------------------------------------------- Captured log call --------------------------------------------------------------------------------------------------------------------
INFO brew_dash.tilts.services:services.py:33 2022-02-20 20:57:32.196975+00:00
INFO brew_dash.tilts.services:services.py:34 Aggregating 4 new tilt readings
I used cookiecutter-django to start the app and am using the default settings. I'm not sure what configs to share which might be helpful to troubleshoot this. I can add some if there are any ideas.
EDIT
pytest.ini:
[pytest]
addopts = --ds=config.settings.test --reuse-db
python_files = tests.py test_*.py
Using docker-compose -f local.yml run --rm django pytest . -rP --capture=no
_______________________________________________________________________________________________________ TestAggregateTiltReadings.test_initial_run _______________________________________________________________________________________________________
------------------------------------------------------------------------------------------------------------------- Captured log call --------------------------------------------------------------------------------------------------------------------
INFO brew_dash.tilts.services:services.py:33 2022-02-21 02:38:09.635703+00:00
INFO brew_dash.tilts.services:services.py:34 Aggregating 4 new tilt readings
_______________________________________________________________________________________________________ TestAggregateTiltReadings.test_initial_run _______________________________________________________________________________________________________
------------------------------------------------------------------------------------------------------------------- Captured log call --------------------------------------------------------------------------------------------------------------------
INFO brew_dash.tilts.services:services.py:33 2022-02-21 02:38:09.635703+00:00
INFO brew_dash.tilts.services:services.py:34 Aggregating 4 new tilt readings
EDIT 2 the offending test:
@pytest.mark.django_db
class TestAggregateTiltReadings:
def test_initial_run(self, tilt_hydrometer_factory, tilt_reading_factory, caplog):
next_cutoff_dts = timezone.now()
tilt = tilt_hydrometer_factory.create()
# Ensure there's a few TILT readings as would be expected for an initial run
tilt_reading_factory.create(tilt_hydrometer_uuid=tilt)
tilt_reading_factory.create(tilt_hydrometer_uuid=tilt)
tilt_reading_factory.create(tilt_hydrometer_uuid=tilt)
tilt_reading_factory.create(tilt_hydrometer_uuid=tilt)
# last_cutoff_date equaling None makes this an initial run test
gravity, temp = aggregate_tilt_readings(tilt, None, next_cutoff_dts)
assert "Aggregating 4 new tilt readings" in caplog.text
assert is_gravity_valid(int(float(gravity) * 1000))
assert is_temp_valid(temp)
| |
doc_23530962
|
I like both methods; the first is tidier and takes less code, the second can identify exactly where your accessing some logic from which can provide some clarity when looking over the code. Just wondering if there are pros/cons for either or if this is just a personal preference, currently I use a combination but would like to keep consistant.
Imports Core.Tech
Public SomeClass
Public Function New()
Return TechMethods.SomeTechFunction()
End Function
End Class
Public SomeClass
Public Function New()
Return Core.Tech.TechMethods.SomeTechFunction()
End Function
End Class
A: Another consideration you should make when it comes to Imports is if there will be multiple classes (or both methods and classes) with the same name.
For instance, there are three different timers in the System.Timers, System.Threading, and System.Windows.Forms namespaces. If you wanted to use one of the first two timers in a WinForms application, you would want to explicitly mention the namespace or create an alias.
'without imports
Dim timer As System.Threading.Timer
'imports
Imports System
Dim timer As Threading.Timer
'alias
Imports ThreadingTimer = System.Threading.Timer
Dim timer As ThreadingTimer
A: This is mostly a matter of style but the predominant pattern in .Net is to leverage Import statements. Not using an Import statement causes unnecessary verbosity in your code. Especially when you consider the extremely long names of some .Net namespaces.
For example
Dim map As New System.Collections.Generic.Dictionary(Of System.Int32, System.String)
' vs ...
Dim map As New Dictionary(Of Int32, String)
As I mentioned this is mostly a matter of style but there are some cases where it matters. Most importantly is the use of extension methods. The usefulness of this feature is severely limited if you don't use any Import statements because it will restrict it to extension methods defined in the current namespace (goodbye LINQ).
| |
doc_23530963
|
I'm wondering if there's a way to use a rewriteCond rule to identify the subdomain, and then treat all URLs loaded on that page as though they are from stock.website.com/stock, but only having stock.website.com in the adress bar?
At the moment, I have the standard htaccess rules for a zend application.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
A: I suggest that you could use Zend Route Hostname for your solution as Zend will route the requests (not htaccess) to specific modules based on hostname, so you stresses on query string url would be not an issue then.
Basically, you can add to your application.ini like below (for modules only):
resources.router.routes.stock.type = "Zend_Controller_Router_Route_Hostname"
resources.router.routes.stock.route = "stock.yourwebsite.com"
resources.router.routes.stock.defaults.module = "stock"
resources.router.routes.transaction.type = "Zend_Controller_Router_Route_Hostname"
resources.router.routes.transaction.route = "transaction.yourwebsite.com"
resources.router.routes.transaction.defaults.module = "transaction"
Then the rest just let Zend handle it.
Hope this would help you!
A: RewriteCond %{HTTP_HOST} ^(.*)\.website\.com$ [NC]
RewriteRule ^(.*)$ /%1$1
The RewriteCond should match whatever.website.com
The RewriteRule then maps the URL from whatever.website.com/path to whatever.website.com/whatever/path.
This ruleset would go between your existing RewriteRules and you would not terminate it with [L] so that the index.php rule could act on the resulting URL.
| |
doc_23530964
|
Harry Maths 80
Harry Physics 67
Daisy Science 89
Daisy Physics 90
Greg Maths 70
Greg Chemistry 79
I know that reducer iterates over each of the unique key, hence I am going to get 3 output key value pairs with name and total marks. But I need the name of the student with the total highest mark ie. Reducer output -> Daisy 179
Following is the reduce function I have written :
static int maxMark = 0;
static Text name = new Text();
public static class Reduce extends MapReduceBase implements
Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException{
int totalMarks = 0;
while(values.hasNext())
{
totalMarks+=values.next().get();
}
if (totalMarks > maxMark){
maxMark = totalMarks;
name = key;
output.collect(name, new IntWritable(maxMark));
}
}
But this logic is going to output the previously saved student's name and mark as well!
I can solve this problem if I know the number of input keys to the reducer before the reducer is even called, so that when the reducer iterates over the last key (name), I can call output.collect(name, new IntWritable(maxMark)); once..
So, is there a way to find the number of input keys to the reducer? Or else, what are the other alternatives to get one single output from reducer?
A: You need two map reduce jobs. The first will total up the marks by name, irrespective of group. Then you can run a job with a mapper that turns the keys and values around, so the key is the sum of marks from the previous step, making sure to use a descending comparator. Configure this job to use only a single reducer task and it can flag itself to ignore all but the first call to reduce.
| |
doc_23530965
|
3, 4
3, 5
5, 6
7, 3
8, 9
8, 1
8, 2
9, 8
Or as a graph:
1 2 3-4 5-6 7 8-9
|-------------|
|-----------|
|---|
|-------|
That is there are two clusters 3,4,5,6,7 and 1,2,8,9. The root number is the smallest number of a cluster. Here 3 and 1. I would like to know which algorithms I can use to extract a list like this:
3, 4
3, 5
3, 6
3, 7
1, 2
1, 8
1, 9
A: An algorithm similar disjoint set union algorithm can help you:
*
*Initialize N disjoint subset, each subset has exactly one number, and root of number i(r(i)) is i.
*For each edge (u, v), you can assign:
t = min(r(u), r(v))
r(u) = t
r(v) = t
*
*For each i with i != r(i), you can write out [r(i) - i].
| |
doc_23530966
|
Can we launch into any specific screen within the app?
We currently have support for launching Hangouts from our app, and we would like to add Duo support as well.
A: Found this in the truecaller source code. Can't get to work, but hope it helps. I'm using Kotlin.
val I = Intent("com.google.android.apps.tachyon.action.CALL")
i.'package' = "com.google.android.apps.tachyon"
i.data = Uri.parse("tel: $phone") // phone is the phone number your to a function
i.putExtra(com.google.android.apps.tachyon.extra.IS_AUDIO_ONLY, false)
startActivity(i)
A: Use this :-
Intent intent = getPackageManager().getLaunchIntentForPackage("com.google.android.apps.tachyon");
startActivity(intent);
| |
doc_23530967
|
log file name :
abc.log.2019041607
abc.log.2019041608..
contents of the log file like this
R_MT|D:1234|ID:413|S:1
R_MT|D:1234|ID:413|S:1
R_MT|D:1234|ID:413|S:1
R_MT|D:1234|ID:413|S:1
R_MT|D:1234|ID:413|S:1
R_MT|D:1234|ID:413|S:1
R_MT|D:1234|ID:413|S:1
R_MT|D:1234|ID:413|S:1
R_MT|D:1234|ID:413|S:1
R_MT|D:1234|ID:413|S:1
R_MT|D:1234|ID:413|S:0
R_MT|D:1234|ID:413|S:0
R_MT|D:1234|ID:413|S:0
R_MT|D:1234|ID:413|S:0
R_MT|D:1234|ID:413|S:0
k_MT|D:1234|ID:414|S:1
k_MT|D:1234|ID:414|S:1
k_MT|D:1235|ID:413|S:1
k_MT|D:1235|ID:413|S:1
I am writting a shell script, which when executed it look for the files which gets created in last 5 minutes(Last 5 files, 1 file gets created every minute), open each file one by one and do process, i.e create a output.txt file which contains, R_MT|D:1234|ID:413 for this combination total count having 's' as 0 gets stored in "submited" column, 's'=1 gets stored in notsubmitted column
my output.txt need to look like this:
Type, Number,ID,submitted,notsubmitted
R_MT,D:1234,ID:413,5,10
R_MT,D:1234,ID:414,0,2
R_MT,D:1235,ID:413,0,2
I have used this to get the submitted and notsubmitted values:
zcat abc.log.2019041607.gz |grep "R_MT"|awk -F"|" '{print $2","$3","$4}'|sort|uniq -c
5 D:1234,ID:413,S:0
10 D:1234,ID:413,S:1
2 D:1234,ID:414,S:1
2 D:1235,ID:413,S:1
by above command i am getting the count but i am not getting how can I assign it to a variable so that i can write into the fields "submitted" and "notsubmitted" in the output file, and I am not getting how to obtain the last 5 minutes files?
please help me in this thanks alot!
A: Try this command
find . -name 'abc.log.*' -mmin -5
. can be changed to any path you want.
-mmin represents the last modified 5 minutes ago
This command will result in a list of files created in the past 5 minutes. Then save into a temp. file and read one line at a time to process those file to your liking.
A: For one file:
First make the stream easy for processing with awk (it could be done all in awk, for a slightly better performance):
sed -nr 's/\|/,/g;s/(^R_MT,.*),S:([^ ]) *$/\1 \2/p' <(zcat abc.log.2019041607.gz)
Result (after adding the lines I suggested as a comment to your question)
R_MT,D:1234,ID:413 1
R_MT,D:1234,ID:413 1
R_MT,D:1234,ID:413 1
R_MT,D:1234,ID:413 1
R_MT,D:1234,ID:413 1
R_MT,D:1234,ID:413 1
R_MT,D:1234,ID:413 1
R_MT,D:1234,ID:413 1
R_MT,D:1234,ID:413 1
R_MT,D:1234,ID:413 1
R_MT,D:1234,ID:413 0
R_MT,D:1234,ID:413 0
R_MT,D:1234,ID:413 0
R_MT,D:1234,ID:413 0
R_MT,D:1234,ID:413 0
R_MT,D:1234,ID:414 1
R_MT,D:1234,ID:414 1
R_MT,D:1235,ID:413 1
R_MT,D:1235,ID:413 1
And now count them in awk, using array a for the fieldnames.
sed -nr 's/\|/,/g;s/(^R_MT,.*),S:([^ ]) *$/\1 \2/p' <(zcat abc.log.2019041607.gz) |
awk '{a[$1]; if ($2>0) notsub[$1]++; else submit[$1]++;}
END {for (i in a) print i "," submit[i]+0 "," notsub[i]+0;}
'
For 5 files first determine how you want the results.
Each file a different outputfile: use a loop like
while IFS= read -r filename; do
... <( zcat "${filename}") ...
done < <(find datalogs -type f -name "abc*" -mmin -5)
Results from the 5 files added to one sum
... <( find datalogs -type f -name "abc*" -mmin -5 -exec zcat {} \;) ...
| |
doc_23530968
|
The widget works well when the two applications are in the same domain, but not in different domains. After the AuthenticationManager.SignIn(), the authentication not works and the user is redirected to login page. If I try login via "login page", this not works too, for being in a different domain and within the iframe.
I tried implement this, but it didn't solve: https://learn.microsoft.com/pt-br/aspnet/samesite/system-web-samesite.
Here is the code I used to authenticate by token:
[AllowAnonymous]
public async Task<ActionResult> LoginByToken(string token, string returnUrl)
{
var user = GetUserByToken(token);
if (user != null)
{
await SignInAsync(user);
return RedirectToLocal(returnUrl);
}
else
throw new Exception("The user was not authenticated!")
}
How can I make it works? Thanks for any help!
Note: the problem reported below occur in Chrome and Edge, but not in Firefox.
A: PROBLEM RESOLVED!!!
I found the answer here: https://learn.microsoft.com/pt-br/aspnet/samesite/csmvc
The configuration in the web.config not worked in my case. I needed to change the CookieAuthentication in the partial class Startup (/App_Start/Startup.Auth.cs), in the method ConfigureAuth like this:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
//---------------------------------
// It resolve the problem
CookieSameSite = SameSiteMode.None,
CookieHttpOnly = true,
CookieSecure = CookieSecureOption.Always,
//---------------------------------
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
Note: the "src" in the iframe needed to be published in https.
| |
doc_23530969
|
*
*if The website is opened on ios phone, ipad... to launch a specific deep link.
*if The website is opened on android phone ... to launch a specific deep link.
*if The website is opened on desktop pc ... to launch a specific link.
Thank you!
A: You can use HTTP Header.
See: https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Through the User-Agent field you can get the browser version etc. Other header could be interesting for you, too.
| |
doc_23530970
|
Would there be any way to manually set the location of all my labels, WITH a layout manager?
A: If you want to have a canvas in the middle and then labels on any of the 4 sides, you could use a BorderLayout, like so:
JPanel framePanel = new JPanel(new BorderLayout());
JPanel triangleCanvas = ...
framePanel.add(triangleCanvas, BorderLayout.CENTER);
JPanel northLabels = ...
framePanel.add(northLabels, BorderLayout.PAGE_START);
JPanel southLabels = ...
framePanel.add(southLabels, BorderLayout.PAGE_END);
JPanel eastLabels = ...
framePanel.add(eastLabels, BorderLayout.LINE_END);
JPanel westLabels = ...
framePanel.add(westLabels, BorderLayout.LINE_START);
frame.getContentPane().add(framePanel);
The tricky part will be if you want to somehow align where your labels are depending on the currently drawn triangle (or whatever is in the container), but hopefully you don't want to do that.
*
*How to Use BorderLayout
A: You say that you want to draw the labels at irregular places e.g. at corners and at the sides the dhapes. Then I would recommend to use drawString(String s, int x, int y) in the Graphics2D API. So place the labels and draw then when you draw the figure.
See Lesson: Working with Text APIs for more advanced options like e.g. Fonts and Font metrics.
When you want to specify the exact position of labels, is the only case when you shouldn't use an Layout Manager.
| |
doc_23530971
|
A: I don't know about APIs, but you might be able to get what you want using a Policy with Security Settings in the Domino Directory. This is administrative configuration, and doesn't use an API or any programming.
A Policy with Security Settings can set "required password quality". I've never modified this option, but I think that it would affect the initial password for new users, and existing users only if they change their password.
It probably has no effect on existing users if they don't change their password.
If you wanted to force users to change their password to comply with a higher quality, there's a separate option for "required change interval", but no way (that I can see) to only enforce that for low-quality passwords.
| |
doc_23530972
|
Using Puppet and Vagrant in Windows, how can I import and set up website bindings to a certificate?
| |
doc_23530973
|
I'm triying to convert an ordinary class in a QObject, so i can use this as a worker to connect with other QThread. After I converted my class in a QObject, I have experienced many multiple definition issues. Suppose that my class now looks like this:
#ifndef MYCLASS_HPP
#define MYCLASS_HPP
#include "common.hpp"
#include <qtGui>
namespace Bial
{
class Image;
class Myclass : QObject{
Image *img;
signal:
void mySignal();
public:
void f();
}
#include "Image.hpp"
namespace Bial{
void Myclass::f(){
}
}
#endif //MYCLASS_HPP
MyClass is a simplification of the Platefinder class. Thai is too big to put here;
The issue occurs in the moc_platefinder.o file of this class ans in many functions of my entire library. Totaling 289 multiple definitions issues :
mainwindow.o:/home/lellis/Dropbox/Lellis_Diet/bin/../diet/inc/../bial/File.hpp:1677: first defined here
Entire compiler output
Sorry for my bad english.
A: Shouldn't you include 'Q_OBJECT'(http://qt-project.org/doc/qt-4.8/signalsandslots.html) here? :
class Myclass : QObject{
Q_OBJECT // <-- here
signal:
void mySignal();
public:
void f();
Image *img;
}
Edit: Generally 'multiple definitions of ...' can be repared with 'static' (ie 'static void f()')
Edit: Did you look here? Multiple definitions error: one in my file and one in the moc file.
A: I haven't tried my answer but:
*
*#include QObject make no sense; you could use #include instead;
*In a class derived by QObject you have to add a Q_OBJECT macro in his definition;
*#endif appears in a wrong position;
Then, your code should look like this:
#ifndef MYCLASS_HPP
#define MYCLASS_HPP
#include "common.hpp"
#include <QtGui>
namespace Bial
{
class Image;
class Myclass : QObject{
Q_OBJECT
Image *img;
signal:
void mySignal();
public:
void f();
}
#endif //MYCLASS_HPP
#include "Image.hpp"
namespace Bial{
void Myclass::f(){
}
}
| |
doc_23530974
|
{% for item in search.results %}
{% if search.terms == 'thevendor' %}
{% else %}
{% include 'search-result' %}
{% endif %}
{% endfor %}
I tried to figure out how to write the code to hide these products in a better way. I tried product.vendor like below but when I search for those products individually they are not hidden. The code:
{% for item in search.results %}
{% if product.vendor == 'thevendor' %}
{% else %}
{% include 'search-result' %}
{% endif %}
{% endfor %}
Can someone tell me what I'm missing here? It seems it doesn't know what product.vendor is but when I print out who the vendor is, it displays the vendor. I don't understand why it's not hiding the products that are associated with this vendor.
A: {% for item in search.results %}
{% if item.product.vendor == 'thevendor' %}
{% else %}
{% include 'search-result' %}
{% endif %}
{% endfor %}
This should work.
| |
doc_23530975
|
*
*angular 1.3.8
*angular-mocks 1.3.8
*karma 0.13.19
*jasmine 2.4.1
*node 0.10.33
*OS: Windows 7
*Browser: PhantomJS 2.1.3
The problem is, the service I wish to test (MyService) is not injected in the test file by the angular-mocks lib (i.e. the 'inject' method does nothing). My code looks as follows:
main.js
(function() {
'use strict';
angular.module('module', [ 'ngCookies', 'ngSanitize' ]);
})();
service.js
(function () {
'use strict';
angular.module('module')
.factory('MyService', MyService);
MyService.$inject = ['Dependency'];
function MyService(Dependency) {
return {
method: method
};
function method() {
// do something
}
}
})();
service.spec.js
(function () {
'use strict';
describe('MyService', function () {
var deferred;
var MyService;
var DependencyMock = {};
beforeEach(module('module'));
beforeEach(module(function ($provide) {
$provide.value('Dependency', DependencyMock);
}));
beforeEach(inject(function (_MyService_, $q) {
MyService = _MyService_; // nothing is injected here
deferred = $q.defer(); // nothing is injected here
}));
it('should be injected', function () {
console.log(deferred); // logs 'undefined'
expect(MyService).toBeDefined(); // fails
});
describe('method', function () {
it('should have this method', function () {
expect(MyService.method).toBeDefined(); // fails as MyService is undefined
expect(typeof MyService.method).toBe('function');
});
});
});
})();
karma.conf.js
// list of files / patterns to load in the browser
files: [
'libs/angular/angular.js',
'libs/angular-mocks/angular-mocks.js',
'src/js/main.js',
'src/js/services/service.js',
'src/js/tests/unit/service.spec.js'
]
package.json
"devDependencies": {
"bower": "1.7.7",
"grunt": "0.4.5",
"grunt-contrib-clean": "0.7.0",
"grunt-contrib-concat": "0.5.1",
"grunt-contrib-connect": "0.11.2",
"grunt-contrib-copy": "0.8.2",
"grunt-contrib-cssmin": "0.14.0",
"grunt-contrib-jshint": "0.12.0",
"grunt-contrib-less": "1.1.0",
"grunt-contrib-uglify": "0.11.0",
"grunt-karma": "0.12.1",
"grunt-lesshint": "1.1.1",
"grunt-ngdocs": "0.2.9",
"grunt-processhtml": "0.3.9",
"jasmine-core": "2.4.1",
"karma": "0.13.19",
"karma-cli": "0.1.2",
"karma-coverage": "0.5.3",
"karma-jasmine": "0.3.6",
"karma-phantomjs-launcher": "1.0.0",
"karma-spec-reporter": "0.0.24",
"phantomjs-prebuilt": "2.1.3"
}
bower.json
"devDependencies": {
"angular": "1.3.8",
"angular-animate": "1.3.8",
"angular-cookies": "1.3.8",
"angular-mocks": "1.3.8",
"angular-soap": "2.1.1",
"bootstrap": "3.3.6",
"font-awesome": "4.5.0",
"angular-translate": "2.9.0",
"angular-sanitize": "1.3.8"
}
My guess is that this is somehow related to angular-mocks.
A: I've figured out the problem. It seems that one of the Angular module dependencies was not included by Karma, which caused the 'inject' to not work.
A: Try injecting an instance of your service inside each it() method.
eg:
it('should be injected', inject(function ('MyService') {
console.log(deferred);
expect(MyService).toBeDefined();
}));
describe('method', function () {
it('should have this method', inject(function ('MyService') {
expect(MyService.method).toBeDefined();
expect(typeof MyService.method).toBe('function');
}));
});
| |
doc_23530976
|
<Extension()>
Public Function ToUtcIso8601(ByVal dt As Date) As String
Return String.Format("{0:s}Z", dt)
End Function
But I also need a Nullable version of the same method... how exactly do I do this?
This is what I was thinking, but I'm not sure if this is the right way
<Extension()>
Public Function ToUtcIso8601(ByVal dt As Date?) As String
Return If(dt, Nothing).ToUtcIso8601()
End Function
or another option
<Extension()>
Public Function ToUtcIso8601(ByVal dt As Date?) As String
Return If(Not dt Is Nothing, ToUtcIso8601(dt), Nothing)
End Function
I'm just not sure the "right" way to do this.
Edited
This actually works, But...
Public Function ToUtcIso8601(ByVal dt As Date?) As String
Return If(Not dt Is Nothing, ToUtcIso8601(dt.Value), Nothing)
End Function
Is this the right way to do this?
A: I'd go for the second option. Unfortunately, when using extension methods on a Date struct, Date? extension methods are not applicable, otherwise you could just declare one extension for the Date? type. You will have to take a similar approach to the one you already have in order to support both types.
| |
doc_23530977
|
I'm wondering if there is an easier way of implementing the uniqueChars function in c90.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#define MAXGRIDHW 9
typedef enum bool{ false = 0, true = 1 } bool;
typedef struct node{
char grid[MAXGRIDHW][MAXGRIDHW];
int height;
int width;
int parent;
} Node;
bool uniqueChars(Node* b);
void setHeightWidth(Node* b, int h, int w);
void clearNode(Node* b);
int main (void)
{
Node shelf1[10];
char testArr2[3][4] = {{"z.."},
{"q.."},
{"z.."}};
clearNode(&shelf1[2]);
memcpy(&shelf1[2].grid, testArr2, 7);
setHeightWidth(&shelf1[2], 3, 4);
assert(uniqueChars(&shelf1[2]) == true);
return 0;
}
bool uniqueChars(Node* b)
{
int i, j, chars = 0;
bool appears;
for (i = 0; i < MAXGRIDHW; i++) {
for (j = 0; j < MAXGRIDHW; j++) {
b->grid[i][j] = toupper(b->grid[i][j]);
if (b->grid[j] == b->grid[i]) {
appears = true;
break;
}
}
if (!appears) {
chars++;
}
}
if (b->height < chars || b->width < chars) {
return false;
}
return true;
}
void setHeightWidth(Node* b, int h, int w)
{
b->height = h;
b->width = w;
}
A: Count the number of occurrences of each character:
int numchars[256];
memset(numchars, 0, 256*sizeof(int));
for (int i = 0; i < MAXGRIDHW; i++) {
for (int j = 0; j < MAXGRIDHW; j++) {
++numchars[toupper(b->grid[i][j])];
}
}
And then traverse the numchars array to see which chars occur only once.
| |
doc_23530978
| ||
doc_23530979
|
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
Excel.Worksheet worksheet2 = workbook.Sheets[2];
// populate worksheets with some data
DataTable2Worksheet(tableMain, worksheet, verSize);
DataTable2Worksheet(tableExtra, worksheet2, 0);
string fileName = @"D:\MyTests\ExcelTests\newFile";
if (File.Exists(fileName ))
{
File.Delete(fileName );
}
workbook.SaveAs(fileName);
workbook.Close();
Marshal.ReleaseComObject(application);
but this creates a new file (which cannot be macros enabled programmatically). If I want to output the workbook to existing file
string existingFile = @"D:\MyTests\ExcelTests\template.xlsm"
the method
workbook.SaveAs(existingFile );
won't work. So, what should I do instead? Thanks.
A: Save the file specifically in xlOpenXMLWorkbookMacroEnabled format:
string existingFile = @"D:\MyTests\ExcelTests\template.xlsm"
workbook.SaveAs(existingFile, 52);
| |
doc_23530980
|
I tried doing this
grep -A5 'pattern' *.*
Here I get the following output
filename
line1
filename
line2
filename
line3
filename
line4
filename
line5
I however just want the lines as the output and not the file names. My ideal output would be
filename
line1
line2
line3
line4
line5
I also tried the following but they didn't work.
grep -l 'pattern' *.* | head -5
head -5 < grep -l 'pattern' *.*
Any idea on how to do this on the shell?
A: If you want grep to omit filenames from its output when it has multiple input files, then you should use the -h option (or you can use --no-filename instead if your grep happens to be the GNU flavor).
Also, the -A5 option gives (up to) 5 lines of context around each match. If that's what you want then well and good, but it looks like perhaps you instead want to limit grep to 5 matches. That would be -m5 for max 5 per file, or pipe it into head -5 if you want only 5 overall.
A: This should work for you:
cat *.* | grep -A 5 'pattern'
Yet please clarify if you want to show only (1) total 5 lines, (2) 5 lines per file, or (3) 5 lines after each pattern match. My answer fits the last one, i.e. 5 lines after each pattern match.
| |
doc_23530981
|
Does anyone know where it should be added or if there is anything else I need to update.
A: It depends on theme you're using, check theme documentation and source.
Some themes, like apollo are supports favicon config parameter (theme_config.favicon parameter in_config.yml).
If theme does not support a custom favicon, then just add file source/favicon.ico and it will be requested by browser automatically.
A: I use Landscape, the default theme at time of writing.
blog\blog\node_modules\hexo\node_modules\hexo-cli\assets\themes\landscape\_config.yml
At the bottom of the file, you'll find a section titled Miscellaneous.
# Miscellaneous
google_analytics:
favicon: blog\themes\landscape\source\css\images\favicon.ico
twitter:
google_plus:
fb_admins:
fb_app_id:
Windows can be directionally-challenged when it comes to slashes, so try the opposite direction if you use PC. This took some fudging on my part, and I was able to use an .ico file as well as a .png.
If you're still in need of a placeholder image, I've used Favicon.cc and had great results.
A: you can add the favicon.ico in the source floder, and add a line in the blog/_config.yml
favicon: favicon.ico
so, you know the source is the root path
A: I think all the other answers are so confused.
Now just three steps to add a favicon to your hexo-blog website, and I take next theme as example:
*
*First, download your favorite imagename.ico image file from network or you make one by yourself.
*Second, rename the imagename.ico file to favicon.ico, then move it to that folder: blog/themes/next(the theme folder you are using now)/source/images/.
*Finally, modify the code in file blog/themes/next/_config.yml at that line to the same as below:
# Put your favicon.ico into `hexo-site/source/` directory.
favicon: images/favicon.ico
Done!
A: Konstantin Pavlov is right.
for example, I use hexo-theme-next theme.
I change code in themes/next/_config.yml.
# Put your favicon.ico into `hexo-site/source/` directory.
favicon: images/favicon.ico
I put my favicon.ico in themes/next/source/images/favicon.ico
well Done.
A: Add this to the head part of the html code...
<head>
<title>Test Page</title>
<link rel="icon" type="image/png" href="http://www.w3.org/Icons/w3c_home">
</head>
For more on this have a look at the W3C site : How To FavIcon
It's also good to inspect the page source by looking at the console as it will report if there were any issue retrieving the icon.
| |
doc_23530982
|
Root composer.json requires grimzy/laravel-mysql-spatial dev-l9-compatibility, found grimzy/laravel-mysql-spatial[dev-test-issue-26, dev-fix/locale-polyfill, dev-master, dev-srid, dev-mysql-5.6, dev-mysql 2.0.0, ..., 2.2.3, 3.0.0, 4.0.0, 4.0.x-dev (alias of dev-master), 5.0.0]
but it does not match the constraint.
facing this error when i upgrade my laravel version 8 to 9.
i have include this package also in my composer.json
"grimzy/laravel-mysql-spatial": "*",
A: Seems the issue is with your MySQL version, not in PHP.
If you're just upgrading PHP and not MySQL, then you have to use
composer require grimzy/laravel-mysql-spatial:^1.0
| |
doc_23530983
|
I have done lot of homework but couldn't find a solution.
A: Messages are consumed from queues, not exchanges.
The way to figure out original exchange that message was published to is to use Firehose Tracer plugin (maybe even with rabbitmq-tracing
plugin alongside).
Alternatively, you may figure out original exchange by comparing queues bindings with message routing key. This usually work well in most cases, unless you have really wired publishers and routing logic.
P.S.: finally, if you have at least read access to publishers code you can figure out where each messages goes from.
| |
doc_23530984
|
do some text replacement and write modified contents to a new file. I am new to Erlang and
want to use simple code with no error handling (use it from Erlang shell).
I have tried:
File = file:read_file("pbd4e53e0.html").
But when using
string:len(File).
I get
exception error: bad argument in function length/1
called as length({ok,<<">}) in call from string:len/1 (string.erl, line 66).
Next step is to do replacement:
re:replace(File, "<a href=\'pa", "<a href=\'../pa/pa", [{return, list}]).
Question 1: How should I read the file into an Erlang variable?
Question 2: Is the replacement ok?
A: For the first question, file:read_file/1 returns a tuple of {Status, Result}, so the assignment should rather be like:
{ok, File} = file:read_file("pbd4e53e0.html").
Second, File will be a binary, not a string, so you need to convert it to a string first:
Content = unicode:characters_to_list(File).
(You can provide the encoding argument as well)
Then string:len(Content) will work as expected.
As for the replacements part, it's generally a very bad idea to use regex with HTML, but from the API point of view looks ok.
| |
doc_23530985
|
I want to, via PHP, get all rows from both tables ordered by the "date" field.
Example:
-----------------------------------------------
name | category | date
-----------------------------------------------
PSO | Food | 2015-09-16
TSI | Sport | 2015-10-12
-----------------------------------------------
-----------------------------------------------
film | date
-----------------------------------------------
Harry Potter | 2015-09-19
Star Wars | 2015-11-14
-----------------------------------------------
The result I expect is that:
PSO, Food, 2015-09-16
Harry Potter, 2015-09-19
TSI, Sport, 2015-10-12
Star Wars, 2015-11-14
How can I do that?
PS: each row of tables will be a div on my webpage and these div's must be ordered by date.
A: Looks like you are looking for UNION but the result won't be same as what you posted; since UNION poses restriction that both table must have same number of columns but you can insert a NULL for missing column though like below.
select * from (
select name,
category,
`date` from table1
union
select film, null, `date`
from table2) xx
order by `date`;
A: Try
SELECT name, category, concat('') AS film, date
FROM TABLE_1 ORDER BY `date`
UNION
SELECT concat('') AS name, concat('') AS category, film, date
FROM TABLE_2
ORDER BY `date` ;
Since UNION expects to have the column names similar while doing union operation you might need to use custom columns with empty values.
A: select name ,
category,
date from table1
union all
select film as name , null as category , date
from table2
order by date;
Make sure the aliases of both table are same and ordered currectly.....
| |
doc_23530986
|
A: Without going into the technicalities you should be looking at separating the "mouse" click event into "mouse" down and "mouse" up events.
Perform the selection on the up event if the pointer location hasn't changed since the down event. So you will need to store the pointer location on the down event.
Then you can handle the pointer move event to perform the scrolling.
A: I got it to work. It wasn't as trivial as I had hoped. By the way, this should work on normal windows, not just windows mobile. It went something like this:
When you create the window (as a child window of the main window)
HWND createCustomDrawArea(const LPCTSTR className, const HWND hWndParent) {
WNDCLASS wndClass = {
CS_HREDRAW | CS_VREDRAW,
(WNDPROC)wndProc,
0,
0,
hInstMain,
NULL,
0,
(HBRUSH)GetStockObject(HOLLOW_BRUSH),
0,
className
};
RegisterClass(&wndClass);
return CreateWindow(
className,
className,
WS_CHILD | WS_TABSTOP,
0, 0, 0, 0,
hWndParent,
NULL,
hInstMain,
NULL
);
}
Then in the main function (the main message loop):
while(GetMessage(&msg, NULL, 0, 0)) {
if(!handleScrollingMessages(msg.hwnd, msg.message, msg.wParam, msg.lParam) && !TranslateAccelerator(msg.hwnd, NULL, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
I did this so that once the finger (mouse) is down, you can move your finger elsewhere (that's still in the same program, but can be outside the scrolling window), and it will continue to scroll until you let go (mouse up). The message handler looks like this:
inline BOOL handleScrollingMessages(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
static BOOL mouseIsDown = FALSE;
static BOOL isScrolling;
static POINT firstMousePos;
static POINT lastMousePos;
POINT currentMousePos;
switch(message) {
case WM_MOUSEMOVE:
if(!mouseIsDown) {
return FALSE;
}
GetCursorPos(¤tMousePos);
scrollText(currentMousePos.y - lastMousePos.y);
if(!isScrolling && (
firstMousePos.x currentMousePos.x + FINGER_SCROLL_SENSITIVITY ||
firstMousePos.y currentMousePos.y + FINGER_SCROLL_SENSITIVITY
)) {
isScrolling = TRUE;
}
lastMousePos = currentMousePos;
return TRUE;
case WM_LBUTTONDOWN:
if(hWnd == whichPrimaryIsVisible) {
if(!mouseIsDown) {
GetCursorPos(&firstMousePos);
lastMousePos = firstMousePos;
mouseIsDown = TRUE;
isScrolling = FALSE;
}
return TRUE;
}
return FALSE;
case WM_LBUTTONUP:
if(mouseIsDown) {
mouseIsDown = FALSE;
if(isScrolling) {
isScrolling = FALSE;
} else {
if(hWnd == whichPrimaryIsVisible) {
jumpToSong(HIWORD(lParam));
}
}
return TRUE;
}
return FALSE;
}
return FALSE;
}
In the normal message handler, you have to catch the WM_ERASEBKGND and WM_PAINT messages:
case WM_ERASEBKGND:
if(hWnd == whichPrimaryIsVisible) {
drawBackground(hWnd, (HDC)wParam);
return 1;
}
return DefWindowProc(hWnd, message, wParam, lParam);
case WM_PAINT:
if(hWnd != hWndMain && drawWindowSection(hWnd)) {
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
You then have to draw both the background and the text (foreground) separately. The scrolling function looks like this:
inline void scrollText(const int mouseChange) {
RECT wholeAreaRect;
RECT invalidatedRect;
scrollPos += mouseChange;
GetClientRect(whichPrimaryIsVisible, &wholeAreaRect);
ScrollWindowEx(whichPrimaryIsVisible, 0, mouseChange, NULL, &wholeAreaRect, NULL, &invalidatedRect, SW_ERASE | SW_INVALIDATE);
UpdateWindow(whichPrimaryIsVisible);
}
Keep in mind that whichPrimaryIsVisible is the scrolling window (global variable), and that scrollPos is a global int.
The only other thing that remains is drawBackground() and drawWindowSection(). They are long and convoluted in my program as I get them to do other things too (that are related to drawing the window BTW). If you really want that code, then send me a message or something. Also let me know if I've posted things the right way, as I'm new to posting on forums etc.
| |
doc_23530987
|
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <queue>
using namespace std;
const int maxVert = 'M' + 1;
const int maxAns = maxVert - 'A';
struct edgeType
{
char vertex1, vertex2;
int weight;
};
struct qType
{
char vertex1, vertex2;
int weight;
qType* link;
};
enum colorType { white, gray, black };
colorType color[maxVert];
void init(int adj[maxVert][maxVert], colorType color[maxVert], edgeType ans[maxAns]);
void createGraph(int adj[maxVert][maxVert]);
void printGraph(int adj[maxVert][maxVert], ofstream& outf);
void createQueue(qType*& qHead, qType*& qTail);
bool emptyQueue(qType*& qHead, qType*& qTail);
void deQueue(qType* qHead, qType* qTail, char& vertex1, char& vertex2, int& weight);
void enQueue(qType* qHead, qType* qTail, char vertex1, char vertex2, int weight);
void mst(qType* qHead, qType* qTail, int adj[maxVert][maxVert], colorType color[maxVert], edgeType ans[maxAns], char startPoint, ofstream& outf);
int main()
{
ofstream outf("output.ot");
int adj[maxVert][maxVert];
edgeType ans[maxAns];
qType* qHead;
qType* qTail;
init(adj, color, ans);
createGraph(adj);
outf << "2D Adjacency Matrix:" << endl;
printGraph(adj, outf);
createQueue(qHead, qTail);
mst(qHead, qTail, adj, color, ans, 'A', outf);
return 0;
}
void init(int adj[maxVert][maxVert], colorType color[maxVert], edgeType ans[maxAns])
{
for (int i = 0; i < maxVert; i++)
{
for (int j = 0; j < maxVert; j++)
{
adj[i][j] = 0;
adj[j][i] = 0;
}
}
for (int i = 0; i < maxVert; i++)
{
colorType color = white;
}
for (int i = 0; i < maxAns; i++)
{
ans->vertex1 = 0;
ans->vertex2 = 0;
ans->weight = 0;
}
}
void createGraph(int adj[maxVert][maxVert])
{
char vertex1, vertex2;
int weight;
fstream inf("input.dat");
while (!inf.eof())
{
inf >> vertex1 >> vertex2 >> weight;
adj[vertex1][vertex2] = weight;
adj[vertex2][vertex1] = weight;
}
}
void printGraph(int adj[maxVert][maxVert], ofstream& outf)
{
int i, j;
outf << setw(5) << " ";
for (j = 'A'; j < maxVert; j++)
{
outf << setw(3) << (char)j;
}
outf << endl;
for (i = 'A'; i < maxVert; i++)
{
outf << setw(5) << char(i);
for (j = 'A'; j < maxVert; j++)
{
outf << setw(3) << adj[i][j];
}
outf << endl;
}
outf << endl;
}
void createQueue(qType*& qHead, qType*& qTail)
{
qHead = new qType;
qTail = new qType;
qHead->vertex1 = 'A';
qTail->vertex1 = 'A';
qHead->vertex2 = 'A';
qTail->vertex2 = 'A';
qHead->weight = 0;
qTail-> weight = 0;
qHead->link = qTail;
qTail->link = NULL;
}
bool emptyQueue(qType*& qHead, qType*& qTail)
{
return qHead->link == qTail;
}
void deQueue(qType* qHead, qType* qTail, char& vertex1, char& vertex2, int& weight)
{
qType *c;
c = qHead->link;
qHead->link = c->link;
vertex1 = c->vertex1;
vertex2 = c->vertex2;
weight = c->weight;
delete c;
}
void enQueue(qType* qHead, qType* qTail, char ivertex1, char ivertex2, int weight)
{
qType* knew, * next, * previous;
knew = new qType;
knew->vertex1 = ivertex1;
knew->vertex2 = ivertex2;
knew->weight = weight;
previous = qHead;
next = qHead->link;
while ((next != qTail) && (weight >= next->weight))
{
previous = next;
next = next->link;
}
previous->link = knew;
knew->link = next;
}
void mst(qType* qHead, qType* qTail, int adj[maxVert][maxVert], colorType color[maxVert], edgeType ans[maxAns], char startPoint, ofstream& outf)
{
//char vertex1, vertex2;
//int weight;
int counter = 0;
enQueue(qHead, qTail, startPoint, 'X', 0);
color[qHead->vertex1] = gray;
while (!emptyQueue(qHead, qTail))
{
deQueue(qHead, qTail, qHead->vertex1, qHead->vertex2, qHead->weight);
if (color[qHead->vertex1]!=black && qHead->weight !=0)
{
ans[counter].vertex1 = qHead->vertex1;
ans[counter].vertex2 = qHead->vertex2;
ans[counter].weight = qHead->weight;
counter++;
for (qHead->vertex2 = 'A'; qHead->vertex2 > 'M'; qHead->vertex2++)
{
if (adj[qHead->vertex1][qHead->vertex2] != 0 && color[qHead->vertex2] != black)
{
enQueue(qHead, qTail, qHead->vertex2, qHead->vertex1, adj[qHead->vertex1][qHead->vertex2]);
color[qHead->vertex2] = gray;
}
}
color[qHead->vertex1] = black;
}
}
outf << ans->vertex1 << ans->vertex2 << ans->weight;
}
I am able to set up my adjacency matrix and assign weight values, but I am running into issues with my mst function. I'm not sure If I'm using the correct variables to pass to my queue. I'd like to be able to print out the edges and weights that span this tree but I am stuck. Any help would be appreciated.
| |
doc_23530988
|
import numpy as np
import pandas as pd
df=pd.DataFrame({'Mbr ID':['ID0001','ID0002','ID0003','ID0004'],
'Receipts':[3,5,12,5],
'Spending':[130,22,313,46],
'Grade':['A','B','A','B']
})
df=df.set_index(['Mbr ID'])
I am trying to analyze the dataframe by grades, and want to see how many unique IDs there are within each grade. But I run into problem with counting Mbr IDs, as the column is used as Index.
agg_func={'Customer':pd.Series.nunique,'Receipts':np.sum,'Spending':np.sum}
df.groupby('Grade').agg(agg_func)
KeyError: 'Mbr ID'
What should I normally do in this situation?
A: use a lambda instead
agg_func = {
'Grade': lambda s: s.index.nunique(),
'Receipts': 'sum',
'Spending': 'sum'
}
df.groupby('Grade').agg(agg_func).rename(columns={'Grade': 'Customer'})
| |
doc_23530989
|
(function($){
$("#block-footermenu a.nav-link").each(function(e) {
console.log($(e).attr('title'));
});
})(jQuery);
but in the console, I'm getting undefined what I'm missing here?
Following is my HTML
<nav role="navigation" aria-labelledby="block-footermenu-menu" id="block-footermenu" class="block block-menu navigation menu--footer-menu">
<ul class="nav ul_align">
<li class="nav-item">
<a class="nav-link" title="Sitemap" href="/us/sitemap">Sitemap</a>
</li>
</ul>
</nav>
A: You should use $(this) to refer back to the element on which you have clicked.
(function($){
$("#block-footermenu a.nav-link").each(function(e) {
console.log($(this).attr('title'));
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav role="navigation" aria-labelledby="block-footermenu-menu" id="block-footermenu" class="block block-menu navigation menu--footer-menu">
<ul class="nav ul_align">
<li class="nav-item">
<a class="nav-link" title="Sitemap" href="/us/sitemap">Sitemap</a>
</li>
</ul>
</nav>
| |
doc_23530990
|
Check the following links to see the design ( ignore the percentage, also the gradient is optional ).
The problem is I can't figure how to have a rounded element at the end of the bar.
I would also like the chart to be animated ( please check Easy Pie Chart for the animation )
I tried with a lot of jQuery plugin but without success.
The idea is to have the chart generated by jQuery getting the information needed ( percentage / bar color / track color ) from the div.
e.g
<div class="chart" data-percent="73" bar-color="#225333" track-color="#ffffff">73%</div>
Any help would be really appreciated.
A: its not totally correct.I does not know jquery.But I think this can be done by html5 canvas. first of all you will have to make a circle of radius R in canvas and then use blue colored arc function in canvas to make arc of D degree.Obviously there should be a javascript function that take the value D and make the appropriate arc and then you can place the blue dot at x = xCenter + radius * cos(angle) y = yCenter + radius * sin(angle). I will provide you the exact code after some time.
A:
var x = 200;
var y = 200;
var r = 50;
var ROTATION = 0;
function setcanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.translate(x,y);
ctx.rotate((Math.PI/180)*(-ROTATION));
ctx.translate(-x,-y);
ctx.clearRect(0,0,c.width,c.height);
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle="black";
ctx.arc(x,y,r,0,2*Math.PI);
ctx.stroke();
}
function getPoint(c1,c2,radius,angle) {
return [c1+Math.cos(angle)*radius,c2+Math.sin(angle)*radius];
}
function setPercent(uplimit) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.translate(x,y);
ROTATION=270;
ctx.rotate((Math.PI/180)*ROTATION);
ctx.translate(-x,-y);
ctx.lineWidth = 4;
ctx.strokeStyle="red";
ctx.arc(x,y,r,(Math.PI/180)*(uplimit),0);
ctx.stroke();
ctx.beginPath();
var a = getPoint(x,y,r,(Math.PI/180)*(uplimit))[0];
var b = getPoint(x,y,r,(Math.PI/180)*(uplimit))[1];
nr = 5;
ctx.arc(a,b,nr,0,2*Math.PI);
ctx.lineWidth = 2;
ctx.fillStyle = 'red';
ctx.fill();
ctx.fillStyle = "red";
ctx.stroke();
}
function callcanvas(degree) {
setcanvas();
setPercent(360-degree);
}
var degree = 180;
var start = 0;
var it = window.setInterval(function() {
callcanvas(start);
start++;
if(start == degree) {
start = 0;
window.setInterval(it);
}
},20);
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
A:
//======== CONFIGURATION WINDOW
//======== i made this configuration code here you can change value and experiment
var x = 200;//set the x - center here
var y = 200;//set the y - center here
var r = 50;//set the radius here
var linewidth=50;//set the line width here
var SET_COLOR="#00FFFF";//set the color here
var SET_PERCENTAGE = 85 //set the percentage here
//========
var loaded = false;
window.onload = function() {
var status=document.getElementById('status');
status.style.top=y+'px';
status.style.left=x+'px';
loaded = true;
}
var ROTATION = 0;
function setcanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.translate(x,y);
ctx.rotate((Math.PI/180)*(-ROTATION));
ctx.translate(-x,-y);
ctx.clearRect(0,0,c.width,c.height);
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle="black";
ctx.arc(x,y,r+(linewidth/2),0,2*Math.PI);
ctx.globalAlpha=0.1;
ctx.stroke();
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle="black";
ctx.arc(x,y,r-(linewidth/2),0,2*Math.PI);
ctx.stroke();
}
function getPoint(c1,c2,radius,angle) {
return [c1+Math.cos(angle)*radius,c2+Math.sin(angle)*radius];
}
function setPercent(uplimit) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.translate(x,y);
ROTATION=270;
ctx.rotate((Math.PI/180)*ROTATION);
ctx.translate(-x,-y);
ctx.lineWidth = linewidth;//40
ctx.strokeStyle=SET_COLOR;
ctx.arc(x,y,r,(Math.PI/180)*(uplimit),0);
ctx.globalAlpha=1;
ctx.stroke();
ctx.beginPath();
var a = getPoint(x,y,r,(Math.PI/180)*(uplimit))[0];
var b = getPoint(x,y,r,(Math.PI/180)*(uplimit))[1];
nr = linewidth/2;
ctx.lineWidth = 1;
ctx.strokeStyle="white";
ctx.arc(a,b,nr,0,2*Math.PI);
ctx.fillStyle="white";
ctx.fill();
ctx.stroke();
ctx.beginPath();
var a = getPoint(x,y,r,(Math.PI/180)*(uplimit))[0];
var b = getPoint(x,y,r,(Math.PI/180)*(uplimit))[1];
nr = linewidth/2-3;
ctx.lineWidth = 1;
ctx.strokeStyle="white";
ctx.arc(a,b,nr,0,2*Math.PI);
ctx.fillStyle=SET_COLOR;
ctx.fill();
ctx.stroke();
}
function callcanvas(degree) {
setcanvas();
setPercent(360-degree);
}
var degree = parseInt((SET_PERCENTAGE*360)/100);
var start = 0;
var it = window.setInterval(function(){
callcanvas(start);
start++;
if(start == degree) {
start = 0;
window.setInterval(it);
}
if(loaded)
document.getElementById("status").innerHTML = parseInt((start*100)/360)+'%';
},1);
<div style='position:absolute;top:0px;left:0px;' id='status'>
0%
</div>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
| |
doc_23530991
|
sealed class Layer
data class ShapeLayer(var type: LayerType) : Layer
data class TextLayer(var type: LayerType) : Layer
data class ImageLayer(var type: LayerType) : Layer
LayerType is just some enum which can be used to distinguish which type should this object have.
I thought I could add Adapter this way:
class LayerAdapter{
@FromJson
fun fromJson(layerJson: LayerJson): Layer {
return when (layerJson.layerType) {
LayerType.SHAPE -> PreCompLayer()
LayerType.SOLID -> SolidLayer()
LayerType.Text -> TextLayer()
}
}
}
Where LayerJson would be object which has every possible field of all LayerTypes.
Now the problem is:
Cannot serialize abstract class com.example.models.layers.Layer
I could try to use interface, but I don't think it would be correct to use empty interface in this.
A: Yes, you can create a custom type adapter to parse json according to the layerType like this:
class LayerAdapter {
@FromJson
fun fromJson(layerJson: LayerJson): Layer = when (layerJson.layerType) {
LayerType.SHAPE -> ShapeLayer(layerJson.layerType, layerJson.shape ?: "")
LayerType.TEXT -> TextLayer(layerJson.layerType, layerJson.text ?: "")
LayerType.IMAGE -> ImageLayer(layerJson.layerType, layerJson.image ?: "")
}
@ToJson
fun toJson(layer: Layer): LayerJson = when (layer) {
is ShapeLayer -> LayerJson(layer.type, shape = layer.shape)
is TextLayer -> LayerJson(layer.type, text = layer.text)
is ImageLayer -> LayerJson(layer.type, image = layer.image)
else -> throw RuntimeException("Not support data type")
}
}
Here I have make some changes to your data class for clarity (an extra property to each of the Layer type, e.g. shape for ShapeLayer):
sealed class Layer
data class ShapeLayer(val type: LayerType, val shape: String) : Layer()
data class TextLayer(val type: LayerType, val text: String) : Layer()
data class ImageLayer(val type: LayerType, val image: String) : Layer()
//LayerJson contains every possible property of all layers
data class LayerJson(val layerType: LayerType, val shape: String? = null, val text: String? = null, val image: String? = null) : Layer()
enum class LayerType {
SHAPE, TEXT, IMAGE
}
Testing code:
val moshi = Moshi.Builder()
.add(LayerAdapter())
.build()
val type = Types.newParameterizedType(List::class.java, Layer::class.java)
val adapter = moshi.adapter<List<Layer>>(type)
//Convert from json string to List<Layer>
val layers: List<Layer>? = adapter.fromJson("""
[
{"layerType":"SHAPE", "shape":"I am rectangle"},
{"layerType":"TEXT", "text":"I am text"},
{"layerType":"IMAGE", "image":"I am image"}
]
""".trimIndent())
layers?.forEach(::println)
//Convert a list back to json string
val jsonString: String = adapter.toJson(layers)
println(jsonString)
Output:
ShapeLayer(type=SHAPE, shape=I am rectangle)
TextLayer(type=TEXT, text=I am text)
ImageLayer(type=IMAGE, image=I am image)
[{"layerType":"SHAPE","shape":"I am rectangle"},{"layerType":"TEXT","text":"I am text"},{"image":"I am image","layerType":"IMAGE"}]
Edit:
You can add the adapter as usual when you are trying to parse other object which contain Layer. Suppose you have an object like this:
data class LayerContainer(val layers: List<Layer>)
Testing code:
val moshi = Moshi.Builder()
.add(LayerAdapter())
.build()
val adapter = moshi.adapter(LayerContainer::class.java)
val layerContainer: LayerContainer? = adapter.fromJson("""
{
"layers": [
{"layerType":"SHAPE", "shape":"I am rectangle"},
{"layerType":"TEXT", "text":"I am text"},
{"layerType":"IMAGE", "image":"I am image"}
]
}
""".trimIndent())
layerContainer?.layers?.forEach(::println)
val jsonString: String = adapter.toJson(layerContainer)
println(jsonString)
A: It turned out that my code was actually correct from beginning!
Problem was with field declaration inside data Class:
data class LayerContainer(var/val layers: List<Layer>)
It works with val, and doesn't work with var!
Kotlin somehow creates different code down below.
This is my final code for this part of model:
@JvmSuppressWildcards var layers: List<Layer>
| |
doc_23530992
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
if ($) {
$(document).ready(
function() {
$('ul li span').click(
function() {
$(this).parent().children('ul').hide();
}
);
}
);
}
</script>
</head>
<body>
<ul>
<li><a href="">My Controls <span class="arrow">↑</span></a>
<ul>
<li><a href="">My Profile</a></li>
</ul>
</li>
</ul>
</body>
</html>
This is the full code I'm using. When I click the span tag I want it to hide the inner <ul>. I assumed that this would access the span element, parent() the li, and children() the ul contained instead the li, but this doesn't seem to be the case. Am I making some sort of stupid mistake here?
TIA.
A: When you click on the span you get the parent of the spam (the a) and look for its ul children — it doesn't have any.
You need to go up another level.
A: You can shorten this by navigating directly to the parent (note: parents('selector') climbs the ancestors until a match, no more .parent().parent()... guessing):
$(this).parents('li').find('ul').hide();
Also, I suggest this for more effect:
$(this).parents('li').find('ul').slideUp();
Your ul elements aren't children of your span or your anchor, they're children of the li they both belong to. Traversing up to this then hiding all ul beneath is what you're after I believe.
A: The following works, clicking the arrow (and only by clicking the arrow, though I suspect that's intentional on your part), hides the child <ul>, in FF3.0.12, Ubuntu 8.04. Though for some reason it seems unnecessarily complex.
<script type="text/javascript">
if ($) {
$(document).ready(
function() {
$('ul li span').click(
function() {
$(this).parent().parent().children('ul').hide(); // Original (modified) technique
// Nick's technique: $(this).parents('li').find('ul').hide();
// My preferred technique: $(this).parents('li').find('ul').toggle();
}
);
}
);
}
</script>
A: 'this' represents DOM element. You need jQuery wrapper for it, $(this). Try
$(this).parent().children('ul').hide();
| |
doc_23530993
|
.
I'd like to be aware of this difference, so it doesn't affect the websites I work on. The wording doesn't suggest a bug in the implementation, but it seems to blame Firefox. Assuming that it wasn't a bug, I'd like to know if Firefox's implementation is deviating from the standard, or if this is another case of the more popular's browser's implementation being considered the "standard."
A: a detailed explanation was posted on Mozilla technical blog (although it's not entirely clear this got to the exact set of heuristics that was assumed)
| |
doc_23530994
|
So when creating the bundle for App1, is webpack going to include the entire Angular 1.4 and 1.5 in it?
A: webpack does not manage versions of libraries. You just say i.e. import angular, where angular is in bower_components.
In your scenario you will face errors/warnings when you install angular 1.5 and module which requires angular 1.4 with bower.
| |
doc_23530995
|
A⊆B
A⊆C
B⊆∃R.D̸
C⊆∃R.D
E⊆∀R.D̸
Tell whether the concept A is satisfiable. So I put A(a) in my ABox and I start the algorithm, getting:
A0={((A̸∨B)∩(A̸∨C)∩(B̸∨∃R.D̸)∩(C̸∨∃R.D)∩(E̸∨∀R.D̸))(a)}.
Then I get:
A1={((A̸∨B),(A̸∨C),(B̸∨∃R.D̸),(C̸∨∃R.D),(E̸∨∀R.D̸))(a)}.
which leads me to:
Ak={((A̸(a)∨B(a)),(A̸(a)∨C(a)),(B̸(a)∨R(a,b)D(b̸)),(C̸(a)∨R(a,c)D(c)),(E̸(a)∨D̸(b)))}.
A̸(a) is a clash with A(a), B̸(a) is a clash with B(a) and C̸(a) is a clash with C(a), so I have:
Ak={((B(a)),(C(a)),(R(a,b)D(b̸)),(R(b,c)D(c)),(E̸(a)∨D̸(b)))}.
Let's see what happens with b's expansion:
Ak+1={((A̸∨B),(A̸∨C),(B̸∨∃R.D̸),(C̸∨∃R.D),(E̸∨∀R.D̸))(b)}.
which leads me to:
Ak+m={((A̸(b)∨B(b)),(A̸(b)∨C(b)),(B̸(b)∨blocked),(C̸(b)∨blocked),(E̸(b)∨D̸(c)))}.
Now D̸(c) clashes with D(c) and B̸(b) clashes with B(b).
And I get it is unsatisfiable, which is wrong. Could somebody please show me where I'm wrong with the application of this tableau algorithm?
| |
doc_23530996
|
branch(branch_id, branch_name, branch_addr, branch_city, branch_phone);
driver(driver_ssn, driver_name, driver_addr, driver_city, driver_birthdate, driver_phone);
license(license_no, driver_ssn, license_type, license_class, license_expiry, issue_date, branch_id);
exam(driver_ssn, branch_id, exam_date, exam_type, exam_score);
**the exam_date is a date
So I am using the tables driver and exam. I would like to somehow check that the exam_date>anotherDate while at the same time checking that exam_score
*EDIT
This is what I came up with but I feel like some of the syntax is illegal. I keep getting a syntax error.
s.executeQuery("SELECT driver_name " +
"FROM driver " +
"WHERE driver.driver_ssn IN " +
"(SELECT e1.driver_ssn" +
"FROM exam e1" +
"WHERE e1.exam_score < " +
"(SELECT e2.exam_score FROM exam e2)" +
"AND e1.exam_date > " +
"(SELECT e2.exam_date FROM exam e2)");
EDIT! I got it working! Thanks for your input everyone!
SELECT driver.driver_name
FROM driver
WHERE driver.driver_ssn IN
(SELECT e1.driver_ssn
FROM exam e1, exam e2, driver d
WHERE e1.exam_score < e2.exam_score
AND e1.exam_date > e2.exam_date
AND e1.driver_ssn=e2.driver_ssn)
A: You will need to do a self join. See this example and work it to your schema.
select d.name,
es.date_taken as 'prev date',
es.score as 'prev score',
es.date_taken as 'new date',
es_newer.score as 'new score'
from driver d
inner join exam_score es
on d.id = es.driver_id
left outer join exam_score es_newer
on d.id = es_newer.driver_id
and es_newer.date_taken > es.date_taken
and es_newer.score < es.score
where es_newer.id is not null
Here is a SQL Fiddle that I made to demonstrate.
A: SELECT returns a set and you cannot compare a single value against a set. You can try something along these lines. This is similar to yours and doesn't handle three exam case :-
SELECT driver_name
FROM driver
JOIN exam e1 ON driver_ssn
JOIN exam e2 ON driver_ssn
WHERE e1.exam_score < e2.exam_score
AND e1.exam_date > e2.exam_date
The query selects all pairs of exams taken by a driver in which the score is less and the date big
A: Simple take on this problem would be getting drivers who take a couple of exams and their second score is lower.
To compare columns from the same table SQL uses self-join. Your join condition should include:
select e1.driver_ssn, e1.exam_type, e1.exam_score as score_before,
e2.exam_score as score_after
exam e1 join exam e2 on (e1.driver_ssn = e2.driver_ssn and
e1.exam_type = e2.exam_type and
e1.exam_date < e2.exam_date and
e1.exam_score > e2.exam_score)
| |
doc_23530997
|
Let's say I create a list
testlist = list(a = 1:3, b = 4:6, c= 7:9)
print(testlist)
$a
[1] 1 2 3
$b
[1] 4 5 6
$c
[1] 7 8 9
I want to create a function where you input either a, b, or c and it returns the values associated with the selected element. What I tried was this
testfunc = function(element){
d = testlist$element
return(d)
}
No matter what you put as the element, the function returns NULL. How should I change the function such that whatever is inputted in (element) is put after the $?
A: We can use [[ instead of $
testfunc = function(element){
d = testlist[[element]]
return(d)
}
-testing
> testfunc("a")
[1] 1 2 3
| |
doc_23530998
|
I know the URI of that file.
I don't want to open that file in my app.
is it possible to know the number of pages of msword file?
if yes how??
A: You could try the Apache API for word Docs:
It has a method for getting the page count:
public int getPageCount()
It will return the page count or 0 if the SummaryInformation does not contain a page count.
| |
doc_23530999
|
@Procedure(name = "SECURITE.P_MAJ_DROITFAM")
public void updateDroitFamille (@Param("v_id_fam") Long idFamille,@Param("v_action_type") Integer cas,@Param("v_user") String userName);
Error log :
Hibernate: {call updateDroitFamille (?,?,?)} 15: 46: 39,946 - ERROR - SqlExceptionHelper.logExceptions: 146 - ORA-06550: Line 1,
column 7: PLS-00201: The identifier 'UPDATEDROITFAMILLE' must be
declared
but procedure name is P_MAJ_DROITFAM and not updateDroitFamille
The problem is that the procedure name has been changed during execution!!? any ideas?
A: What you need to do is put additional configuration on one of your entities do declare the definition of your procedure first in the application:
@NamedStoredProcedureQuery(name = "P_MAJ_DROITFAM", procedureName = "SECURITE.P_MAJ_DROITFAM", parameters = {
@StoredProcedureParameter(mode = ParameterMode.IN, name = "v_id_fam", type = Long.class),
@StoredProcedureParameter(mode = ParameterMode.IN, name = ""v_action_type", type = Integer.class) },
@StoredProcedureParameter(mode = ParameterMode.IN, name = ""v_user", type = Integer.class) })
public class MyEntity{
Then in the repository you would call like:
@Procedure(name = "P_MAJ_DROITFAM")
public void updateDroitFamille (@Param("v_id_fam") Long idFamille,@Param("v_action_type") Integer cas,@Param("v_user") String userName);
You can keep the name of the method.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.