text:
Q: Bash Menu: Return to menu after selection made and executed? I've got a bash script that writes to a file.  at the end of the script I want to display a menu, with line numbers - and have the user be able to select 1 or 2, (etc. up to the number of lines in the file) then have it execute that line.
Up to here is perfect.
However, after the line is executed (say for example it displays another file.)  I'd like to return to the menu and let the user select another number.  Including zero for exiting the menu.
Once the menu is displayed I have the following.  (dumpline being the line of the file read)
     dresult=`sed -n "$dumpline"p "$PWD"/"$myday1"_"$myjob".txt`
     $dresult

But right now - after running the variable $dresult - it exits the shell (where instead I'd like the menu displayed.
Any thoughts?
thank you in advance.

A: Here's another way to do a menu which relies on cat having the ability to number the lines of a file (some versions of cat may not have that - see the second example if this is the case). Both examples are for a simple four-item menu:
while [[ 1 ]]
do
    cat -n menufile
    read -p "Make a selection " choice
    case $choice in
        1|2)
           echo "A or B"
           ;;
        3)
           echo "C"
           ;;
        4)
           break
           ;;
        *)
           echo "Invalid choice"
           ;;
    esac
done

This doesn't require cat -n:
saveIFS="$IFS"
IFS=$'\n'
read -d '' -a menuarray < menufile
IFS="$saveIFS"

for (( i=0; i<${#menuarray[@]}; i++ ))
do
    menu=$menu"$(($i+1))) ${menuarray[i]}"$'\n'
done

while [[ 1 ]]
do
    echo "$menu"
    read -p "Make a selection " choice
    case $choice in
        1|2)
           echo "A or B"
           ;;
        3)
           echo "C"
           ;;
        4)
           break
           ;;
        *)
           echo "Invalid choice"
           ;;
    esac
done

A: My comments on dz's answer are too long for a comment, so I'm posting them here:
Using seq with select would make a redundant-looking menu, with no correlation between it and the display of the lines in $dumpfile:
ls
echo 'hello'

1) 1
2) 2
etc.

You could do something like this instead:
saveIFS=$IFS
IFS=$'\n'
menu=$(< $dumpfile)
PS3="Make a selection: "
select ACTION in $menu QUIT
do
    IFS=$saveIFS
    case ...

A: I think, you need something like a loop. Here is a small skelleton for executing  a selected line from file:
#!/bin/bash

dumpfile="bla.txt"

echo "ls
echo 'hello'" > ${dumpfile}

function do_action {
    line="$( sed -n "${1},1p" "$dumpfile" )"
    (
        eval "${line}"
    )
}

cat -n $dumpfile
nr=$( cat "${dumpfile}" | wc -l )
PS3="select line nr or nr for QUIT: "
select ACTION in $( seq "$nr" ) QUIT
do
    case $ACTION in
        QUIT) echo "exit" ; break ;; #EXIT
        *) do_action "$ACTION" ;;
    esac
done

But be aware of the following:

*

*Using eval might be not allways be a good idea (escaping is hard). Sometimes $line should be sufficient.

*Using a subshell prevents changing variables by executing a line of the file. It also does prevent exiting the script from lines that do normally exits a shell.


text:
Q: Writing Clojure Macro To Generate map Forms I have a sequence of sequences, output from clojure-csv.
(def s1 [[:000-00-0000 "SMITH" "JOHN" 27][:000-00-0001 "FARMER" "FANNY" 28]])

I have a vector of column numbers [0 3] that I want to use to extract data from each sequence.
Rather than writing a function to zip together a variable number of map forms, I thought a macro might do the trick. But, I am having trouble.
This macro accepts a sequence and a column "mask"
   (defmacro map-cols [seq & columns]
    (for [col# columns
        :let [mc# `(map #(nth % ~col# nil) ~seq)]]
        mc#))

(map-cols s1 cols)
ClassCastException clojure.lang.LazySeq cannot be cast to clojure.lang.IFn  bene-csv.core/eval2168

I was hoping to generate the multiple map forms that show up in
the following:
(zipmap (map #(nth % 0 nil) s1) (map #(nth % 1 nil) s1))
{:000-00-0001 "FARMER", :000-00-0000 "SMITH"}

I would appreciate some ideas of what I am doing wrong. I can, of course, just tailor the a function to the number of columns I need to extract.
Thank You.
Edit:
Modified macro
(defmacro map-cols [seq & columns]
    (vec (for [col columns
        :let [mc `(map #(nth % ~col nil) ~seq)]]
        mc)))

(apply zipmap (map-cols s1 cols))

ArityException Wrong number of args (1) passed to: core$zipmap  clojure.lang.AFn.throwArity

A: You are mixing up code that will execute at macro expansion with code that the macro will output. Until you enter a syntax-quote, you don't need to use auto-gensym (col#, mc# in your example). As for the macro output, it must always produce exactly one form. It seems that you are expecting it to produce several forms (one for each col), but that's not how this can work. Your macro output will currently look like
((map #(nth % 0 nil) s1) (map #(nth % 1 nil) s1))

This is a form with two members. The member in the head position is expected to be a function, and the whole form is supposed to be evaluated as a function call.
The way to salvage this is to wrap your for in the macro with a vec and then use (apply zipmap (map-cols s1 cols)).
That answers your immediate question, but the solution will still not make sense: zipmap wants exactly two args, not a variable number of them as you said you want, and the output is a map, not a sequence that zips together your fields. Zipping is achieved using (map vector seq1 seq2 ...).

redpajama_set_name: RedPajamaStackExchange


text:
Q: RDP to home PC with Windows Hello PIN I have a Windows machine at home that is using my Microsoft account, and I login using PIN. How do I RDP to that machine?
In the RDP client, there is no option to sign in using PIN, only password. When I tried to use my MS account + password, it says "The logon attempt failed".
I know I can disable the option "Require Windows Hello sign-in for Microsoft accounts", and just remove the Hello PIN altogether, but I would like to sign in using PIN when I'm using the machine, but at the same time allow me to RDP using either PIN, or username+password.
How do I:

*

*Set the RDP client to sign in using PIN?

*Or... how do I enable the Windows machine to enable login with both PIN and username+password?

This is all at home settings, no AD, no domain-joined, both the host (Windows 10 Professional) and client (Mac) is at home in the same network.

A: Might be late to the party, but I found this post because I was having the same issue.  Same environment and same machines
What I did was go to Settings -> Remote Desktop
Under the User Accounts header, select Select users that can remotely access this PC
In the popup, click Add and then click Advanced and finally click Find Now
Scroll through the list until you find your name and email address that are in the folder for what your PC is named (Farid-PC, Desktop-W7283 or something similar)
Select the user, and then click OK on all the open windows.
You should now be able to RDP to the machine using your Live email address and password

A: Windows 10 professional and higher have Remote Desktop server abilities. Windows 10 Home does not.
According to this forum post, the RDP doesn't play well with Windows Hello. You are probably better off using a traditional password. Here is some more information that could help.

A: Try logging in with a regular account password, after the login fails you still should be able to see the windows login screen (if you entered the correct password). I am connecting to azure so it says: "The sign-in method you are trying to use isn't allowed...", Click OK button, and try looking for "Sign-in options" button. Then it will give you option to login with pin. Type in Windows Hello Pin and you should be able to enter.

A: I know you mentioned that you are using a Mac for the client, but I'm going to assume that Microsoft's RDP client for Mac has a feature similar to the client on Windows that addresses this. I don't have access to a Mac to test.
If you're using the Microsoft Remote Desktop Connection program mstsc.exe, go to the Advanced tab then click the checkbox for "Use a web account to sign in to the remote computer". When you connect a window will open to allow you to enter your credentials.


text:
Q: The equivalent of  using MySQL and Hibernate3 annotations Starting a new project I'd like to use Hibernate annotations with MySQL instead of the configuration files I've used so far.
And I can't seem to find the equivalent of:
    <id name="id" type="long" >
        <generator class="native"></generator>
    </id>

I tried using:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "native")
private long id;

but got:
org.hibernate.AnnotationException: Unknown Id.generator: native

or:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

Give me:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: PROCEDURE projectName.identity does not exist

Does anyone successfully deployed MySQL and Hibernate3 annotations for automatically generating ids?

A: Prior to version 5.0, using the strategy AUTO was the equivalent of using native in a mapping. This used the LegacyFallbackInterpreter:
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
    return id;
}

Since Hibernate 5.0, the default interpreter is the FallbackInterpeter which will either use a SEQUENCE generator or TABLE generator depending on the underlying database.
To use the LegacyFallbackInterpreter, set hibernate.id.new_generator_mappings to false.

A: You might wish to have a look at: http://hibernatepojoge.sourceforge.net/

A: Try using @GeneratedValue(strategy=GenerationType.AUTO).  That should use the MySQL autonum functionality.


text:
Q: How to catch Upgrade event for a SharePoint Hosted App? Our SharePoint Hosted App has a configuration file needs to be updated during App upgrade. I understand that event-handling code can't be used for SharePoint Hosted App. It will be painful for an administrator to visit each App to update the configuration file manually if the app has been deployed to hundreds of subsites.
I was thinking to have the app home page to update the file automatically when a user access the app first time, but it can run into permission issue as not all users can write the file. Now I am thinking of creating a tool for the administrator to update all sites at once, but I don't feel it is a good solution.

A: Been there too. I think best that the config should be in an App Web List or an App Web Property in json form. This way you won't worry for permissions. If you include a version number in your javascript and copy / cross check it with an app weeb property, then you have your own Upgrade event receiver. If the version number in the javascript is not the same with the stored in the App Web Properties, then this time it runs just from an upgrade action.
Even better, keep the version as a string, in the exact same form that there is in the AppManifest.xml.


text:
Q: Better design for blocklists I have 10-12 items which i need to maintain a blocklist for on my system. Which design is better? These are sample columns, much more items to block.
table 1
b_id
b_email
b_name
b_username
b_pagename
b_word
b_IP
comments
table 2
b_id
b_type
text
comments
Basically in table 1, each blocked item is a value in 1 column only, rest are all NULL.
In table 2, each blocked item resides in the only column so there are no NULLs
There are other designs possible too like separate tbl for each item but then there will be lots of tbs just to hold blocklists.

EDIT: The use of this data is to block users from performing certain activities. Each blocked item is used in differnt places. Example:
block_IP = list of IP addresses that the website will block based on detected user's IP
block_name = list of restricted first/last names users cannot use to signup with
block_email = list of restricted emails users cannot use to signup with
block_username = list of restricted usernames users cannot use to get a profile name
block_pagenames = list of restricted page names users cannot create
block_word = abusive words which users cannot use within content of comments, blogs, etc.
and the list goes on...
So basically these are all like individual lookup items. In an ideal world we would have separate tables for each item. But I dont like to idea of having 20-30 tables just to hold blocked items values. Should be an easier way to manage all this. Only issue is some items like block_Word can grow to millions of rows as there are a lot of words that can be blocked in many languages.

A: Check out the Entity-Attribute-Value approach or use a schemaless NoSQL datastore.
http://en.wikipedia.org/wiki/Entity-attribute-value_model
If you're processing the 'blocking' in the middle tier, you can just dump the lists as serialized objects (e.g. JSON) into the table.
I assume you're trying to do something like access control lists, which depending on your plaform you might be able to find a plugin for.


text:
Q: Salesforce - Best way to pass namespace__ (e.g:Apttus__, svmax__ etc) to get('obj').getDescribe().fields.getMap(); method We have a requirement to prefix namespace__ value object at below code. For e.g : For template, need to prefix Apttus__, so the object value will be Apttus_template .
We have multiple managed packages installed and in some cases need to pass Apttus__, in some cases need to pass svmx__ etc . Could you please let me know what is the best way to identify the correct namespace__ value and prefix it to object .
Schema.getGlobalDescribe().get('object').getDescribe().fields.getMap();

A: The namespace prefix is part of the object API name. You should be storing the complete ("fully-qualified") object API name. So if you have an object called apttus__Template__c, you must always use that name to reference it - never Template__c, which is incorrect.
Then, pass the entire fully-qualified API name to any dynamic schema access methods you use:
Schema.getGlobalDescribe().get('apttus__Template__c').getDescribe().fields.getMap();


text:
Q: Wrangling x-axis datetime labels on matplotlib I have a pandas DataFrame with a DateTime index.
I can plot a timeseries from it, and by default it looks fine.
But when I try to print a bar chart from the same DataFrame,  the xAxis labels are ruined (massive overlapping). (Also the spacing of the data is weird (big gaps between sets of bars)
I tried autoformat_xdate(), but that didn't help anything.

This is the simple code fragment I used to generate the charts
entire_df['predict'] = regr.predict(entire_df[X_cols])
entire_df['error'] = entire_df['predict']-entire_df['px_usd_mmbtu']
#entire_df['error'].plot(kind='hist')
fig=plt.figure()
entire_df[['px_usd_mmbtu', 'predict']].plot()
fig2 = plt.figure()
entire_df['error'].plot(kind='bar')
#fig2.autofmt_xdate()              #doesn't help
print (type(error_df.index))

A: Try this:
entire_df['predict'] = regr.predict(entire_df[X_cols])
entire_df['error'] = entire_df['predict']-entire_df['px_usd_mmbtu']

plt.figure(figsize=(15,15))
plt.xticks(rotation = 90) # or change from 90 to 45

#entire_df['error'].plot(kind='hist')

entire_df[['px_usd_mmbtu', 'predict']].plot()
entire_df['error'].plot(kind='bar')


text:
Q: Changing actionBar dropdown background color
How do i change the color of the background where it says "add contact" and "about". Now its kind of grayish, but i want it to be white! This is a actionBar with dropdown, not a spinner. And im not using that actionbarsherlock thing.

A: For example, in you exisiting parent Style definition, add just the android:popupMenuStyle attribute as shown below:
<style name="Theme.Example" parent="@android:style/Theme.Holo.Light">
    <item name="android:popupMenuStyle">@style/PopupMenu.Example</item>
    .......
    .......
</style>

And override the android:popupMenuStyle attribute by defining your style:
<style name="PopupMenu.Example" parent="@android:style/Widget.Holo.Light.ListPopupWindow">
    <item name="android:popupBackground">@drawable/menu_dropdown_panel_example</item>
</style>

The @drawable/menu_dropdown_panel_example is this:

You can either choose to use an image similar to the one above, or use an Color resource.
And this is for the default ActionBar. Not the ActionBarSherlock. ;-)
ActionBar styles can be easily created using this cool website: http://jgilfelt.github.com/android-actionbarstylegenerator/. I usually experiment a little here before deciding on the style. Plus, it lets you download the styles and all necessary resources. Just plug them in your app and you are good to go. :-)
UPDATED: I think I caused some confusion which has resulted in the loss of the shadow on your app's drop-down. You may have replaced all the <items> in your Style that I listed in the original suggestion. The edit should fix that.
UPDATE 2:
Use these image resources instead of the @android:color/white value you are currently using. These are in the order of XHDPI, HDPI and MDPI. Save them and use them in the Style definition.

A: Try to get styles from ActionBarStyleGenerator service. It has preview and makes all necessary drawable, xml and styles.
There you can easily find and change required color and then find it in sources (in your case it is android:popupBackground).

A: You can simple override itemBackground item in your theme:
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="android:itemBackground">@color/skyBlue</item>
</style>


text:
Q: How to run Erlang in arm64 Docker image on x86_64 host How can my docker containers run Erlang commands with the linux/arm64/v8 platform on my x86_64/amd64 host?
I am trying to build a multi-platform Docker image following the official documentation. My build is failing when running build steps with erlang. Following this build failure to the underlying cause: Erlang commands return segmentation fault when emulating arm64 on the x86_64 hosts, even though arm/v7 works.
I have tested this across two machines: Windows 10, WSL 2 Ubuntu 20.04, Docker Desktop, x84_64; Ubuntu 20.04, x86_64. I have tested qemu versions 6.2.0 and 7.0.0-28 using their respective tags on tonistiigi/binfmt to install emulators.
Steps to reproduce on either x86_64 host, assuming Docker is already installed:
$ docker run --privileged --rm tonistiigi/binfmt --install all
{
  "supported": [
    "linux/amd64",
    "linux/arm64",
    "linux/riscv64",
    "linux/ppc64le",
    "linux/s390x",
    "linux/386",
    "linux/mips64le",
    "linux/mips64",
    "linux/arm/v7",
    "linux/arm/v6"
  ],
  "emulators": [
    "qemu-aarch64",
    "qemu-arm",
    "qemu-mips64",
    "qemu-mips64el",
    "qemu-ppc64le",
    "qemu-riscv64",
    "qemu-s390x"
  ]
}

$ docker run --rm -it --platform linux/arm64 erlang:latest /bin/bash
root@d7f9b846f13a:/# uname -m
aarch64
root@d7f9b846f13a:/# erl
qemu: uncaught target signal 11 (Segmentation fault) - core dumped
Segmentation fault

$ docker inspect erlang:latest --format '{{.Os}}/{{.Architecture}}/{{.Variant}}'
linux/arm64/v8

Above, platform linux/arm64 is aliasing to linux/arm64/v8. Running erl fails with a segmentation fault. I expect it to work the same as linux/arm/v7, which is able to start an erl session as below.
$ docker run --rm -it --platform linux/arm/v7 erlang:latest /bin/bash
root@5a786052f0e4:/# uname -m
armv7l
root@5a786052f0e4:/# erl
Erlang/OTP 25 [erts-13.1.1] [source] [32-bit] [smp:2:2] [ds:2:2:10] [async-threads:1]

Eshell V13.1.1  (abort with ^G)
1>

$ docker inspect erlang:latest --format '{{.Os}}/{{.Architecture}}/{{.Variant}}'
linux/arm/v7

How can my docker containers run Erlang commands with the linux/arm64/v8 platform on my x86_64/amd64 host?

A: Because of a bug/missing feature in qemu, the erlang JIT segfaults when running. So you need to either compile erlang without the jit, or use an older version of erlang without the jit.
See https://github.com/erlang/otp/pull/6340 for some more details.


text:
Q: Не сохраняется таблица в бд. HSQLDB Изначально я написал проект с использованием spring-jdbc и бд HSQLDB не в mem режиме, сейчас решил переписать с использованием jpa. Когда использовал вариант с spring-jdbc  алгоритм работы был следующий:

*

*Подключаюсь к существующей бд

*Добавляю записи, вношу изменения в существующие записи

Сейчас с использованием jpa у меня таблица создается/удаляется при открытии/закрытии приложения. Почему такое поведение?
Вот код entity:
@Data
@Entity
@Table(name = "goods")
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@AllArgsConstructor
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    long id;
    @Column
    String name;
    @Column
    String description;
    @Column
    LocalDate create_date;
    @Column
    long place_storage;
    @Column
    boolean reserved;
}

Так написан DAO:
public interface ProductDAO extends CrudRepository<Product, Long> {

}

Так написан Service:
@Service
public class ProductServiceImpl implements ProductService {

    private final ProductDAO productDAO;

    @Autowired
    public ProductServiceImpl(ProductDAO productDAO) {
        this.productDAO = productDAO;
    }

    @Override
    public Product findById(long id) {
        return productDAO.findById(id).orElseThrow(NotFoundException::new);
    }

    @Override
    public List<Product> getListProducts() {
        return (List)productDAO.findAll();
    }

    @Override
    public Product updateProduct(Product product) {
        return productDAO.save(product);
    }

    @Override
    public Product saveProduct(Product product) {
        return productDAO.save(product);
    }

    @Override
    public boolean deleteProduct(long id) {
        productDAO.deleteById(id);
        return true;
    }
}

Так подключаюсь к бд:
spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:hsql://localhost/goodsdb
spring.datasource.username=SA


text:
Q: Scale_size_area and scale_radius Good day,
Does anyone understand how R handles scale functions? That's not a circle drawn on a 1:1 scale.
library("ggplot2")
ggplot(mpg, aes(displ, hwy, size = hwy))+geom_point(data=, aes(x=1,y=1), colour="Red", shape=1)+scale_size_area(pi)
ggplot(mpg, aes(displ, hwy, size = hwy))+geom_point(data=, aes(x=1,y=1), colour="Red", shape=1)+scale_radius(1)

R console tells me that:
> scale_size_area()
<ScaleContinuous>
 Range:
 Limits:    0 --    1
> scale_radius()
<ScaleContinuous>
 Range:
 Limits:    0 --    1

A: It is possible to draw geom_point objects with any size you like using scale_radius:
library("ggplot2")
jpeg(filename="circulo.jpeg",width=400 , height=400)
ggplot(mpg, aes(displ, hwy, size = hwy))+geom_point(data=, aes(x=1,y=1), colour="Red", shape=1)+scale_radius(labels=NULL, trans="identity", range=c(165,165), guide=FALSE)
dev.off()

The size of the object varies with the width and height of the image, here's a circle of diameter=1 for a width of 400 and height of 400.

For some strange reason this doesn't work with scale_size_area().


text:
Q: How to get BroadcastReceiver messages in Chrome? I have here an Android device with a build in hardware barcode scanner module with a hardware scan button. I never developed an android app. but i checked the SDK of the device. The sample app uses a BroadcastReceiver to get the result of successful barcode scans.
private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
    ....
}
....

protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter();
    filter.addAction(SCAN_ACTION);
    registerReceiver(mScanReceiver, filter);
}

Because i'm not familiar with java I don't want to develop an app to use this device. I want to use the scanner in chrome browser instead, to work with HTML5, pouchDB & javascript.
So my questions are:
Can I listen for such android Broadcasts in the chrome browser? (how?)
If this is not possible, i think about building a simple app which opens "Chrome Custom Tabs". Is it possible to pass messages from the app to its Chrome custom tabs?
Or is there another way to solve this?


text:
Q: Can't set webhook to viber bot I have some troubles with setting webhook to my viber bot. Every time I wanna set my url viber api returns error.
So I am trying to use this in postman:
Url: https://chatapi.viber.com/pa/set_webhook
{
    "url": "https://gutapi.ml/api/viber/post",
    "event_types":[
      "conversation_started"
   ]
}

When I use code below, viber api returns this result:
{
    "status": 1,
    "chat_hostname": "SN-CHAT-06_"
}

My url is valid and I have ssl sertificate, but it still does not work. Hope you'll help me

A: You have Http error: "500 (Internal Server Error)" on any post request. So problem is on your side :)
Try to send POST request to https://gutapi.ml/api/viber/post (your server) with following payload using Postman and look to your logs.
{
   "status":0,
   "status_message":"ok",
   "event_types":[
      "conversation_started"
   ]
}

Also have a look to Viber API documentation for more details:


text:
Q: Not able to delete the system workflow step in MS CRM 2016 on-premise I have created a system workflow and deleted the workflow itself long back. But still the workflow is running. I cannot find it under normal process. But when I do the advanced find for process entity, I can find the workflow.
When I am open it there is not delete or deactivate button for it.
I tried deleting or deactivating it from the workflow view itself. But it is not allowing me do. Getting the generic error as "Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support" .
Could you please help on this. As this work has few email sending steps, so triggering the emails which I want to stop.
I cannot find it under the setting, all process.

But I can find it when I look for the process, use the "New" view and delete all the predefined conditions. In the below screen I click on the result able to find the workflow.

Workflow image

A: There are two types are Workflow records - Definition & Activation (I'm ignoring Template in this scenario)

For every workflow, two entries will be there. You can use my query to check in DB.

One will have option to Deactivate and the other one don't have.

You are seeing the Activation snapshot record used for execution of WF for lifetime. Take care of those which are already triggered.

If you look at the schema for the Type attribute, there are three values:
1 = Definition
  Definition of a Workflow that is displayed in the application in the "All Processes" view. When you make changes to a workflow, you are making a change to a Workflow definition (or template); if you delete a workflow, you are deleting a workflow definition (or template)
2 = Activation
  Whenever you activate (or publish) a workflow, an Activation record is created. An activation represents a snapshot of the workflow definition taken at activation time. If a Workflow is triggered, the System Job (asyncoperation) links back to the Workflow Activation record. Imagine you activate a workflow, a workflow is triggered and is in the midst of running, when you deactivate the workflow and make a change. In order to not effect the currently running Workflow, it uses the Workflow Activation record. If the workflow is triggered again, it will use the new definition (or workflow activation).
3 = Template
  If you mark a Workflow as a Workflow Template, it will show up on the new Workflow dialog. If you choose to use a template, a copy of the template will be used as a basis of the Workflow.
When a Workflow is deleted from the system, the definition is deleted. However, if the workflow was ever published the Activation will remain for a period of time. Once all of the System Jobs that reference a particular Workflow Activation have completed and have been cleaned up (occurs through a recurring daily bulk delete job), the Workflow Activation will also be deleted.

Reference

A: As specified in the below blog was not able to delete those activation type workflows from UI.
https://sachinbansal.blog/2018/05/02/error-while-deactivating-workflows-should-be-exactly-1-messageprocessingstep-registered-for-workflow-dynamics-365/
We have on-premise CRM, so deleted the workflow from CRM database. It is working fine now.
Before deleting the workflow took full database backup. Run the select query by proving the workflow GUID.
After finding the matching workflow record, deleted them from database. In my case I have found the matching records from the below list of tables in the database.

*

*WorkflowDependencyBase

*WorkflowBase

*WorkflowBaseIds


text:
Q: Get Top 5 Products in Each Category and Subcategory using Entity Framework I am using Entity Framework in my ASP.NET 4.5 web project. I have a table of products, each product with its category and sub-category. A category might not have a sub-category.
Table Products

*

*id

*name

*category_id

*subcategory_id

*date

Table Categories

*

*category_id

*parent_category_id

if the category has a parent_category_id = 0, it's a parent category, else it's a sub category of another category on that same table.
I want to create a query in Entity Framework to retrieve the top 5 products for each subcategory by date from the newest one to the oldest one.
At the end, I want to build tables that show the top 5 latest products for each subcategory.
A product can belogn to only one subcategory.
There are answers for this type of question with one category, but without sub-categories. My question is specific for that specific database structure. Thanks.

A: here is the code for Top 5 products using lembda expressions
YourEntities DBContext = new YourEntities();

List<Category> categories = DBContext.categories.Where(d=> d.category_id!=null).ToList();
List<Product> prodcuts = null;
foreach (var item in categories)
{
    prodcuts = DBContext.Products.Where(d => d.category_id== item.category_id)
                 .OrderByDescending(d => d.date)
                                 .Take(5)
                                 .ToList();
}

A: var q= context.Categories
   .Where( c => c.parent_category_id != 0  )
   .Select( c=> new {
        c.categoryName,
        Products = c.products.OrderByDesc(p => p.DateUpdated)
            .Take (5)
            .Select( p => new {
                p.name,
                p.price
            })
    });


text:
Q: Java:Is it possible to name a collection? I was wanting to put my own unique identifier for my collection instances.
Hashcodes can uniquely identify a collection but that is not what I am looking for. Something like this..
List<Integer> classOneStudentIds = Arrays.asList(123,135);
classOneStudentIds.name = "classOne";
List<Integer> classTwoStudentIds = Arrays.asList(145,138);
classTwoStudentIds.name = "classTwo";

It does not appear to be possible...
Not very relevant when the code is non-recursive and the main program knows what the lists stand for. However, for recursive solutions, I can see it being helpful that the collection is able to identify itself based on what the programmer has named it.
For the following snippet for Tower of Hanoi solution, it would help to not have to use hashCode but rather a meaningful name relevant to the use case at hand..
   Integer elem = pegOne.removeFirst();
   System.out.println("Move element " + elem + " from " +
    pegOne.hashCode());
   pegThree.add(elem);
   System.out.println(" to " + pegThree.hashCode());

Is there a way for a collection to identify itself?

A: It is not possible directly, but have a meaningful Object.
class ListWithId {

   String identifier;
   List<Integer> classStudentIds;
   // more properties you want to add

}

A: class WrapperCollection<T> {

   public String name;
   public List<T> list;

}

The above wrapper collection code will help you achieve the same.
Changes I would do:
1.  Better naming.
2.  Better encapsulation - private fields and immutability.
3.  List operations.


text:
Q: Weird links found in wordpress footer I have a wordpress site where i am removing all the http content to get the ssl padlock. I have done that on the main page but some of the article pages of my website has this code in the footer and therefore chrome is not showing padlock on those pages.
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">

I have no clue what these websites are and i want to remove these lines from my code. I have disabled and deleted all the trackbacks from my site but this code is still there. How can i get rid of them ?
thank you

A: Sometimes a Wordpress appliance service or a plugin makes a change to insert content in the footer of web pages at the web server level. If this was done here this can make it harder to find and remove. If your webserver is Apache try seeing if this file exists:  /etc/apache2/mods-enabled/substitute.conf and then take a look in that file for your offending text and remove it and restart the webserver. This file cannot be edited/removed via WP Admin so has to be done via the command line.


text:
Q: Failed to resolve dependencies (Grails/Spring) I'm trying to run a new Grails project and i get this error
    | Configuring classpath
    | Error Failed to resolve dependencies (Set log level to 'warn' in BuildConfig.groovy for more information):
    - org.springframework:spring-context:3.2.4.RELEASE
    - org.springframework:spring-tx:3.2.4.RELEASE
    - org.springframework:spring-beans:3.2.4.RELEASE
    - org.springframework:spring-core:3.2.4.RELEASE
    - org.springframework:spring-aspects:3.2.4.RELEASE
    - org.slf4j:jcl-over-slf4j:1.7.5
    - org.slf4j:slf4j-api:1.7.5
    - org.springframework:spring-web:3.2.4.RELEASE
    - org.springframework:spring-expression:3.2.4.RELEASE
    - org.springframework:spring-context-support:3.2.4.RELEASE
    - org.springframework:spring-aop:3.2.4.RELEASE
    - org.aspectj:aspectjweaver:1.7.2
    - asm:asm:3.3.1
    - org.aspectj:aspectjrt:1.7.2
    - cglib:cglib:2.2.2
    - org.springframework:spring-webmvc:3.2.4.RELEASE
    - org.springframework:spring-jdbc:3.2.4.RELEASE

and i'm using the sts IDE... what I'm doing wrong?

A: Not sure about the STS issue - one advice I have is to try to get grails run-app running in the command prompt.  That should download all the dependencies correctly onto your file system, and then hopefully STS will pick those up as well.


text:
Q: Does Per-Body Damping Compound With Space Damping in Pymunk? Making some simulations for a project.
My question is does the damping value of a body compound with the damping value of the pymunk space (if there is any)?
For example, if I have a pymunk space, SPACE, with SPACE.damping = 0.9 and then I have a body, BODY, where I set its BODY.update_velocity() method to take a damping value of 0.5, will BODY's damping be 0.9*0.5 (or some other composition) or will it be 0.5?
Let me know if I can make my question more clear and thank you in advance.

A: The damping is used like this:

*

*When stepping the space (space.step), the damping that will be used is calculated by damping = pow(space.damping, dt)

*Next it will call the velocity function of each body in the space, passing in the calculated damping from step 1 (just below the damping calculation in step 1)

*The default velocity function does this calculation to set the velocity:
body.velocity = body.velocity * damping + (gravity + body.force / body.mass) * dt

*And this to set the angular velocity:
body.angular_velocity = body.angular_velocity*damping + body.torque / body.moment * dt
You can find the actual code for step 1&2 here: https://github.com/viblo/pymunk/blob/master/chipmunk_src/src/cpSpaceStep.c#L399
The code for step 3 & 4 here: https://github.com/viblo/pymunk/blob/master/chipmunk_src/src/cpBody.c#L494
(I translated the c code in the source to python/pymunk terms in my answer above)


text:
Q: Differences between REF and RREF Can we say that a system in REF has no solution if the last column of the augmented matrix contains a leading entry. I am a little confused about REF and RREF. Do we need to use RREF to tell whether the system has a solution? OR just REF is enough to tell whether the system has no solutions, infinitely many solutions or one unique solution.

A: REF is enough. RREF will give you the solutions if any, but REF is enough since the necessary and sufficient condition to have no solution is that the rank of the augmented matrix is greater than the rank of the matrix of the linear system.


text:
Q: Socket connection in swift I am learning & developing ios application with swift.I have 2 tabs in my app,so I have 2 view controller.I need to connect socket server.But in which file ?
First tab is showing conversations list and second tab is chat interface.User is sending message from second tab.If someone sends a message to this user,I need to show this message in first tab.
I need to connect socket server but in which file ? I mean example: When message arrives to this user i need to save it to database and show user in second tab.Is view controller file good for this case ?

A: I would recommend checking out Alamofire. It is a fantastic networking library built entirely for Swift and has really picked up in popularity of the past few months. This makes it incredibly easy to call a web service to fetch data.
WebSockets
If you actually need to connect to your server using web sockets, then I'd check out SocketRocket built by the fine folks at Square. Here's a link to their project on Github.
Since you're new to iOS development, I'd suggest a simple architecture where you abstract the network calls out of your view controllers.
ChatManager

*

*Internally manages all networking such as SocketRocket

*Should be a singleton or property on UIApplicationDelegate

*Has public API for sending message

*Sends out notifications when it receives notifications back

class ChatManager {

    // Add property for socket

    class var sharedInstance: ChatManager {
        struct Singleton { static let instance = ChatManager() }
        return Singleton.instance
    }

    init() {
        // Create the socket
    }

    func sendMessage(message: String) {
        // Push the message onto the socket
    }

    // Delegate methods

    func messageReceived(message: String) {
        // Emit the message using NSNotificationCenter
    }
}

View Controller 1

*

*Subscribes to notifications from ChatManager

class ViewController1 : UIViewController {
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        // Register for NSNotification coming from ChatManager
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)

        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

View Controller 2

*

*Subscribes to notifications from ChatManager

*Sends new messages to the ChatManager to push through the socket

class ViewController2 : UIViewController {
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        // Register for NSNotification coming from ChatManager
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)

        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    func userAddedNewChatMessage(message: String) {
        ChatManager.sharedInstance.sendMessage(message)
    }
}


text:
Q: Not able to serialize complex json to an object using GSON? Below is my JSON String which I am getting back by calling from a service API. I have shorten it down by having only three reportRecords for the understanding purpose. In general, it might have ~500 reportRecords
{
   "aggRecords": {
      "reportRecords": [
         {
            "min": 0,
            "max": 12,
            "avg": 0.3699187,
            "count": 246,
            "sumSq": 571,
            "stddev": 1.4779372,
            "median": 0,
            "percentileMap": {
               "95": 4
            },
            "metricName": "TransactionDuration",
            "dimensions": {
               "env": "dev",
               "pool": "titan",
               "Name": "PostProcessing",
               "Type": "PostProcessing"
            },
            "value": 91
         },
         {
            "min": 0,
            "max": 23,
            "avg": 2.3991289E-4,
            "count": 1463031,
            "sumSq": 3071,
            "stddev": 0.045814946,
            "median": 0,
            "percentileMap": {
               "95": 0
            },
            "metricName": "TransactionDuration",
            "dimensions": {
               "env": "dev",
               "pool": "titan",
               "Name": "ResourceContext",
               "Type": "ResourceContext"
            },
            "value": 351
         },
         {
            "min": 0,
            "max": 1209,
            "avg": 1.9203402,
            "count": 7344636,
            "sumSq": 71832774,
            "stddev": 2.4683187,
            "median": 2,
            "percentileMap": {
               "95": 4
            },
            "metricName": "TransactionDuration",
            "dimensions": {
               "env": "dev",
               "pool": "titan",
               "Name": "Client::Sync",
               "Type": "Client::Sync"
            },
            "value": 14104200
         }
      ]
   },
   "minRecordsMap": {}
}

Now From the above JSON response, I need to extract reportRecords whose Name is Client::Sync. Meaning, I need to extract below reportRecords from the above JSON response only.
         {
            "min": 0,
            "max": 1209,
            "avg": 1.9203402,
            "count": 7344636,
            "sumSq": 71832774,
            "stddev": 2.4683187,
            "median": 2,
            "percentileMap": {
               "95": 4
            },
            "metricName": "TransactionDuration",
            "dimensions": {
               "env": "dev",
               "pool": "titan",
               "Name": "Client::Sync",
               "Type": "Client::Sync"
            },
            "value": 14104200
         }

And now I need to parse the above reportRecords for Client::Sync to below object -
public class DataMetrics {

    private String pool;
    private String name;
    private String type;
    private String env;
    private String metricName;
    private String percentile;
    private String median;
    private String stdDev;
    private String sumSq;
    private String count;
    private String avg;
    private String max;
    private String min;

    // getters and setters here
}

So after serializing, above object should look like this -
pool is titan
name is Client::Sync
type is Client::Sync
env is dev
metricNname is TransactionDuration
95th  percentile is 4
median is 2
stdDev is 2.4683187
sumSq is 71832774
count is 7344636
avg is 1.9203402
max is 1209
min is 0

I am using GSON library here and below is what I have tried so far -
private static RestTemplate restTemplate = new RestTemplate();

public static void main(String[] args) {

    String jsonLine = restTemplate.getForObject("some_url", String.class);
    System.out.println(jsonLine); // here jsonLine will give me above big JSON String

    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("aggRecords");
    JsonArray jarray = jobject.getAsJsonArray("reportRecords");

    Type type = new TypeToken<List<DataMetrics>>() {}.getType();
    List<DataMetrics> records = gson.fromJson(jsonArrayThatYouHave, type);

    List<DataMetrics> result = new LinkedList<>();

    for(DataMetrics record : records){
       if(record.name.equals("Client::Sync")){
          result.add(record);
       }
    }
}

But for some reason, some fields in the DataMetrics shows me the data but some fields are coming empty so that makes me think something is wrong in my above code or my DataMetrics class is not right?

A: Generally, for nested objects like dimensions you'll declare another POJO for it
class DataMetrics{
  private String min;
  private String max;
  private String avg;
  /*Insert other members*/

  private Dimensions dimensions;

  public boolean isClientSync(){
    return "Client::Sync".equals(dimensions.Name);
  }
  private class Dimensions{
    private String env;
    private String pool;
    private String Name;
  }
}

Tested:
 public void test() {

 String json = "[{\"min\": 0,\"max\": 1209,\"avg\": 1.9203402,\"count\": 7344636,\"sumSq\": 71832774,  \"stddev\": 2.4683187, \"median\": 2,\"percentileMap\": {\"95\": 4},\"metricName\": \"TransactionDuration\",\"dimensions\": {\"env\": \"dev\",\"pool\": \"titan\",\"Name\": \"Client::Sync\", \"Type\": \"Client::Sync\"},\"value\": 14104200}]";

 final Gson gson = new Gson();
 final Type type = new TypeToken<List<DataMetrics>>() {}.getType();
 final List<DataMetrics> records = gson.fromJson(json, type);

 Assert.assertTrue(records.get(0).isClientSync());
}

For percentileMap you'll want an actual map
private Map<String, Integer> percentileMap;

Also note the member variable names should match the JSON property name exactly

*

*stdDev => stddev

*name => Name

*percentile => percentileMap


text:
Q: adb shell am broadcast - BroadcastReceiver throws nullpointer I'm trying to launch this command:
adb shell am broadcast -a android.provider.Telephony.SMS_RECEIVED --es sms_body "TEXTTEXTTEXT"   -n com.example.name/.receivers.SmsReceiver

And this code throws null pointer exception:
public class SmsReceiver extends BroadcastReceiver {
...

private Context mContext;
private Intent mIntent;

public void onReceive(Context context, Intent intent) {
    mContext = context;
    mIntent = intent;

    String action = intent.getAction();
    if (action.equals(Const.ACTION_SMS_RECEIVED)) {
        String address = "", str = "";

        SmsMessage[] msgs = getMessagesFromIntent(mIntent);

        ...

    }
}

public static SmsMessage[] getMessagesFromIntent (Intent intent){
        Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
        byte[][] pduObjs = new byte[messages.length][];

        for (int i = 0; i < messages.length; i++) {
            pduObjs[i] = (byte[]) messages[i];
        }

        byte[][] pdus = new byte[pduObjs.length][];
        int pduCount = pdus.length;
        SmsMessage[] msgs = new SmsMessage[pduCount];
        for (int i = 0; i < pduCount; i++) {
            pdus[i] = pduObjs[i];
            msgs[i] = SmsMessage.createFromPdu(pdus[i]);
        }
        return msgs;
}

}
And here is the console output:
12-30 15:48:34.724  26032-26032/com.example.name E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.name, PID: 26032
    java.lang.RuntimeException: Unable to start receiver com.example.name.receivers.SmsReceiver: java.lang.NullPointerException
            at android.app.ActivityThread.handleReceiver(ActivityThread.java:2567)
            at android.app.ActivityThread.access$1800(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1341)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.name.receivers.SmsReceiver.getMessagesFromIntent(SmsReceiver.java:60)
            at com.example.name.receivers.SmsReceiver.onReceive(SmsReceiver.java:30)
            at android.app.ActivityThread.handleReceiver(ActivityThread.java:2552)
            at android.app.ActivityThread.access$1800(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1341)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)

Now, here is the tricky part.
My code inside SmsReceiver works for normal SMS messages. When I try to "simulate" this problem, I get this error. Probalby I mixed up something with adb command. I tried to fix it myself, but no luck. Do you have any idea what I did wrong?

A:
Do you have any idea what I did wrong?

You are sending a broadcast with a string extra named sms_body. Your code is not using that. Your code is using a Serializable extra named pdus.

When I try to "simulate" this problem, I get this error.

Use the Emulator Control tab in DDMS, or perhaps the emulator console (e.g., telnet localhost 5554), to send simulated SMS messages to an emulator.
Or, move your SMS-processing logic into a Java class that you can test using JUnit.


text:
Q: How to authorize or not a WebView to load a page url I research how to control a WebView (for Mac application) to allow specific url like iOs with
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
thank you in advance.

A: I finally figured this one out.
Set the WebPolicyDelegate delegate for your WebView instance:
self.webview.policyDelegate = self;

Then implement the – webView:decidePolicyForNavigationAction:request:frame:decisionListener: method in your delegate:
-(void)webView:(WebView *)webView
decidePolicyForNavigationAction:(NSDictionary *)actionInformation
        request:(NSURLRequest *)request
          frame:(WebFrame *)frame
decisionListener:(id < WebPolicyDecisionListener >)listener
{
    int actionKey = [[actionInformation objectForKey: WebActionNavigationTypeKey] intValue];
    if (actionKey == WebNavigationTypeOther)
    {
        [listener use];
    }
    else
    {
        //
        // Here is where you would intercept the user navigating away
        // from the current page, and use `[listener ignore];`
        //

        NSLog(@"\n\nuser navigating from: \n\t%@\nto:\n\t%@",
              [webView mainFrameURL],
              [[request URL] absoluteString]);

        [listener use];
    }

}


text:
Q: Display Multidimensional array via ajax in laravel The form displays data from DB for the entry to be edited. One of the columns is a 2D Array and I do not know how to pass the data.
Tried the normal AJAX display codes
The data coming via COntroller is:
res.credential looks like
[
    [
        "Facebook","x11111111",
        "q1111111","w11111111"
    ],
    [
        "Linkedin","x222222222",
        "q222222","w222222222222"
    ],
    [
        "Twitter","x333",
        "q3333333","w3333333"
    ]
]

The AJAX looks like:
$('.password-edit-btn').on('click', function (){
    var client_sel = $(this).data('id');
if (client_sel) {
    $.ajax({
        type: "GET",
        url: "/get_password_data?id="+client_sel,
        success: function (res) {
            if (res) {
                console.log(res.credential);
                $("#edit-password-client").empty();
                $("#edit-password-client").append('<option>'+ res.client +'</option>');
                $('#edit-password-remarks').val(res.remarks);
            }

// The problematic area is below
            if (res.credential) {
                $.each(res.credential, function (key, value) {
                    console.log(value)
                    $(".add-hf-accounts").append()
                });
            }
        }
    });
}

});
Simply display the data in the div with class "add-hf-accounts".

A: $.each(res.credential, function (key, value) {

  for(var i=0;i<value.length;i++)
  {
    if(i==0)
    {
        $(".add-hf-accounts").append('
'+value[i]+'
');
    }
    $(".add-hf-accounts").append('
'+value[i]+'
');
  }
});

Try It...Will be Work Fine

A: Thanks a lot for the help guys.
The problem was in parsing. I had to use JSON.parse and then it worked beautifully. Below is the final working answer.
if (res.credential) {
                $.each(JSON.parse(res.credential), function (key, value) {
                    $(".add-hf-accounts").append('

Account<select class="form-control" name="account[]"><option value="'+ value[0] +'"> '+ value[0] +'</option></select>

URL<input type="text" class="form-control" placeholder="Accoutn URL" name="url[]" value="'+ value[1] +'">

Username<input type="text" class="form-control" placeholder="User Name" name="user[]" value="'+ value[2] +'">

Password<input type="text" class="form-control" placeholder="Password" name="password[]" value="'+ value[3] +'">

<button class="btn btn-danger remove " type="button"></button>

');
                });
            }


text:
Q: How to make form rounded rectangle or round or triangle I am developing an application in C# and there is a requirement of the form of the main window in rounded rectangle or some times triangle type or round shape.
so, how can I achieve this kind of features in C# 2008

A: I think this is what you're looking for:
http://www.codersource.net/csharp_custom_window_forms.aspx
Also you can google for it, there are plenty examples.

A: Assuming this is on Windows Forms you can check these two articles on MSDN:
http://msdn.microsoft.com/en-us/library/aa289517(VS.71).aspx
http://msdn.microsoft.com/en-us/library/aa984331(VS.71).aspx
You basically have to do the following:

*

*Remove the form border by setting its style to None

*Set a background image that defines the shape of your form

*Set the TransparencyKey of the form to the color that should be transparent

A: Look at the Region property of your form.  You can create a new Region, set its shape using it's various Add... methods and then assign the region to your form's region property.


text:
Q: Determine if a string contains a substring I wanna know how I can find if string A has string B in it without breaking apart the whole string; also finding how much times it repeats using loops. BTW, it doesn't have to be case-sensitive. For example:
public static void main(String[] args) {
    String st = abababajjjabababb;
    String aba = null;
    String st2 = aba;
    int i = 0;
    char ch = st.charAt(i);
    int j;
    for (j = 0;j < st2.length();j = j + 1){
        for (int k = 0; k < st.length(); k = k + 1){
            if(ch == st.charAt(j)) {
                break;
            }
        }
        if(j == st2.length()) {

        }
    }
    System.out.println("the letters in s1 dont repeat in s2");

}

I know how to find if st2 repeats in st but I don't know how to program it to tell me how many times it repeats.
Thanks! I got my answer and I'm done with this program, thanks to you all that gave suggestions.

A: I know how to find if st2 repeats in st but I don't know how to program it to tell me how much times it repeats.
You could remove all occurrences of the substring and then divide by the length of the substring to get the number of occurrences.
String st = "abababajjjabababb";
String st2 = "aba";

int intOccurrences = (st.length() - st.replace(st2, "").length()) / st2.length();

Haven't used Java in a bit so I'm a little rusty.
For your example, this would return:
(17 - 8) / 3
= 3 occurrences

A: you can use count to count how many times it repeats. just declare count as a int. and have count ++ everytime it goes through the loop

A: You can also use StringUtils.countMatches from Apache commons lang to count the number of matches of a substring in a string:
int numOccurrences = StringUtils.countMatches(st, st2);


text:
Q: How to add two gemTypes using Amazon seller api in xml format We are using Amazon seller api's to create listing of our products . Some of our products is having two type of stones in a single earring . So how to add two gemstone details in single product listing . Please share your thoughts or any sample xml file to add these details . Amazon xsd file is not helping us .
thanks !


text:
Q: Unable to access the hive box when app is in background in flutter I am using Hive box to store some key value pairs and want to use those values to filter the incoming push notifications on my flutter project. But this logic works only when the app is in foreground or not closed but if closed it throws this error

MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)

and shows all the push notifications.
The line of code which throws this error is possbily await Hive.initFlutter(); as this is only using getApplicationDocumentsDirectory under the hood.


text:
Q: Dual boot - Windows missing after installing ubuntu I am posting a question and also post the answer as I don't know other way around to help others.
I Have been struggling from last 1 month to make dual boot on my hp laptop its hp g6-2313ax, however finally I did it tonight .
My problem was, I was not getting option to select win7 and laptop was keep on booting with Ubuntu.
Below is the solution
sorry guys if i am doing anything wrong (if yes), please guide me the right way :)

A: I have installed win 7 normally, made 2 partition please make note its in MBR

*

*100 mb system reserved

*50 gigs for my win 7

*Left rest as unallocated
Now after the installation I rebooted the and booted with bootable ubuntu USB
I am not able to see option "alongside" so selected something else
Then coming on to Ubuntu partition (doesnt matter under GPT primary or logical. But if its MBR then strongly logical)
1.20gigs mounted to / (at least 10 gigs required)
2.20gigs mounted to /home ( at least 10 gigs required)
3.10 gigs swap (double of RAM preferred)
4.You may have to create a partion in ubuntu as Fat32 if you want to move files from ubuntu to windows or vice versa (size depends on you requirement and needs. ALSO ITS NOT A MANDATE DRIVE ITS OPTIONAL.)
Then install Ubuntu make sure the directory should be /dev/sda
Once installed reboot your laptop, after reboot it will boot with Ubuntu.
Now to make windows visible we have to update the file named Grub hosted under - /etc/default/grub
To update and make the change in a statement -
GRUB_TIMEOUT=10
And
GRUB_TIMEOUT_HIDDEN=10
For this go to terminal
Type GRUB_TIMEOUT=10 enter then
Type GRUB_TIMEOUT_HIDDEN=10 enter then
Type sudo update-grub enter
Restart the computer I am sure you will be able to see option to choose between windows and Ubuntu
Happy ubuntuing ……….. 
I am so glad finally I did it ……yayy


text:
Q: How to read hyphen zip codes using oledb I have an excel spreadsheet which contains addresses. I'm reading the data from the spreadsheet using OLEDB and storing it into a DataTable in C#.
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + @";Extended Properties=""Excel 8.0;HDR=1;IMEX=1""";

Here's the problem: When I use the DataSet Visualizer, I have an empty string in the zip code field.
12345-1234 --> ""

So I want to correct this behavior so that the zip code appears as it should. If i have to chop off the digits after the hyphen, that would be fine. How can I ensure the zip code gets read?

A: Excel often has its own ideas about how a column should be formatted. For example, if you have a column containing zip codes, some with the Plus 4, others without, it is pretty much a crap shoot as to how that column will be formatted. Maybe Excel will assume that its filled with Zip+4's, maybe it will assume 5-digit Zips, or maybe just numbers. I've worked with these files for years, and I'm convinced Microsoft uses a random number generator in making this decision.
As for your original question, according to this site, CONVERT is a valid SQL scalar function, so maybe something like
SELECT CONVERT(BadField, SQL_CHAR) AS FixedField FROM [Table$]

might work?
My first inclination was to suggest using COM (instead of OleDb) to read the data from the spreadsheet. I'm pretty sure you would be able to read each cell's format and deal with it accordingly, but I always found Excel via COM to be difficult and not terribly fast.


text:
Q: ListView.setAdapter "null Object Reference" Estoy implementando un ListView cargado con una base de Datos Externa, y estoy Obteniendo los datos con un JSON
Este proyecto lo tenia funcionando sin problemas en un Activity, pero al querer implementar el mismo en un fragment me marca estos errores:
Este es el Codigo que tengo en mi Fragment
FragmentNuevas.java
public class FragmentNuevas extends Fragment {

private OnFragmentInteractionListener mListener;
ArrayList<Product> arrayList;
ListView lv;
ProgressDialog pdialog = null;
Context context = null;

public FragmentNuevas() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    lv = (ListView) getActivity().findViewById(R.id.listView);
    arrayList = new ArrayList<>();
    context = getActivity();

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            pdialog = ProgressDialog.show(context, "", "Buscando Noticias...", true);
            new ReadJSON().execute("http://lahuerta.gob.mx/WebService/consulta.php");
        }
    });

    /*lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            Product selectedProduct = arrayList.get(position);

            Intent intent = new Intent(getActivity().getApplicationContext(), Nuevas.class);
            intent.putExtra("nombre", selectedProduct.getName());
            intent.putExtra("fecha", selectedProduct.getFecha());
            intent.putExtra("contenido", selectedProduct.getPrice());
            intent.putExtra("extra1", selectedProduct.getImage());
            startActivity(intent);
        }
    });*/

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_fragment_nuevas, container, false);
}

class ReadJSON extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... params) {
        return readURL(params[0]);
    }
    @Override
    protected void onPostExecute(String content) {

        pdialog.dismiss();
        try {
            JSONArray jsonarray = new JSONArray(content);
            for(int i =0;i<jsonarray.length(); i++){
                JSONObject productObject = jsonarray.getJSONObject(i);
                arrayList.add(new Product(
                        productObject.getString("nombre"),
                        productObject.getString("contenido"),
                        productObject.getString("extra1"),
                        productObject.getString("fecha")

                ));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        CustomListAdapter adapter = new CustomListAdapter(
                getActivity(), R.layout.custom_list_layout, arrayList
        );
        lv.setAdapter(adapter); /*Aqui me da Error*/
    }
}

private static String readURL(String theUrl) {
    StringBuilder content = new StringBuilder();
    try {
        // create a url object
        URL url = new URL(theUrl);
        // create a urlconnection object
        URLConnection urlConnection = url.openConnection();
        // wrap the urlconnection in a bufferedreader
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        // read from the urlconnection via the bufferedreader
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content.toString();
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 *

 * See the Android Training lesson Communicating with Other Fragments for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}
Me marca un error en esta linea:
la Linea 108 en donde da el error es:   lv.setAdapter(adapter);
El LogCat es este:

E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: mx.gob.lahuerta.oficiadepartes, PID: 18201
                    java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
  null object reference
                  at mx.gob.lahuerta.oficiadepartes.FragmentNuevas$ReadJSON.onPostExecute(FragmentNuevas.java:108)
                  at mx.gob.lahuerta.oficiadepartes.FragmentNuevas$ReadJSON.onPostExecute(FragmentNuevas.java:81)
                  at android.os.AsyncTask.finish(AsyncTask.java:667)
                  at android.os.AsyncTask.-wrap1(AsyncTask.java)
                  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Application terminated.

A: Agrega el contexto, en este caso el de la Activity para que puedas ejecutar los métodos, por ejemplo para obtener el contexto:
context = getActivity();   //this;

Para ejecutar runOnUiThread() :
getActivity().runOnUiThread()....

Al convertir tu Activity a Fragment, el Fragment esta relacionado a la Activity que lo contiene, por lo tanto:
Para obtener el contexto dentro de un Fragment lo realizas mediante el método getActivity().

A: En cuanto al error

android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
  null object reference

Se debe a que no encuentra la referencia del ListView en el layout contenedor, en realidad encuentra dentro del layout que carga el Fragment, en este caso fragment_fragment_nuevas.xml  realiza este cambio:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_nuevas, container, false);

    lv = (ListView)view.findViewById(R.id.listView);
    arrayList = new ArrayList<>();
    context = getActivity();

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            pdialog = ProgressDialog.show(context, "", "Buscando Noticias...", true);
            new ReadJSON().execute("http://lahuerta.gob.mx/WebService/consulta.php");
        }
    });

    // Inflate the layout for this fragment
    return view;
}


text:
Q: start repeating alarm from AlarmManager I want to start a service every day from 8am to 6pm. I am using 3 alarms.

*

*For starting alarm2 everyday at 8am.

*For starting service every 1 min.

*To stop alarm2.

Is it the proper way? Also I am unable to start alarm2 from alarm1.
This is code for alarm 1:
    public class AlarmReceiver1 extends BroadcastReceiver {
        int interval;
        @Override
        public void onReceive(Context context, Intent intent) {
            AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent in=new Intent(this,AlarmReceiver2);
            PendingIntent startingIntent = PendingIntent.getBroadcast(context, 0,in, 0);

            long duration = interval * 60 * 1000;
            manager.setRepeating(AlarmManager.RTC_WAKEUP,timeOn.getTimeInMillis(), 86400000,startingIntent);
        }
}

A: Far from enough code to tell if it has been set up properly. There is a good example here on how you should set up the AlarmManager. I'd recommend looking it through if there is something you've missed.
Also as you can see in the example you gotta reset the Alarms every time the phone is rebooted. If you don't the services will not run.


text:
Q: csv.writer with a single quote character I have a row of data that I am trying to write to a .tab file that looks like this:
row = ['07/19/2017/10/33/30', 'gg_ca_18" dishwashers_204454792491_1t1',
       Decimal('369.00'), 1L, '66745355']

I want to leave the single quote not escaped so that it looks like this:
07/19/2017/10/33/30 gg_ca_18" dishwashers_204454792491_1t1  369.00  1   66745355

I am writing to a file using this code:
with open(file_name, 'wb') as outfile:
        a = csv.writer(outfile, delimiter='\t') # ,escapechar=None, quoting=csv.QUOTE_NONE
        a.writerows(row)

I have tried using escapechar=None, quoting=csv.QUOTE_NONE and several variations of this. I always get the error Error: need to escape, but no escapechar set. What is the best way to not escape the single quote in the middle of the line? Is it possible using csv module?

A: You can just use a different quotechar:
with open(file_name, 'w') as outfile:
    a = csv.writer(outfile, delimiter='\t', quotechar="'")
    a.writerow(row)

A: If you do not want to escape anything, it is not a CSV file anymore. Convert each row item to a string, joint the strings into one string, and write it into the file:
line = ' '.join(map(str,row))
#'07/19/2017/10/33/30 gg_ca_18" dishwashers_204454792491_1t1 369.00 1 66745355'
outfile.write(line + "\n")

A: If you want to escape a character, use \.
In you example, it would be \"


text:
Q: SPA Dynamic Routing and Page Rendering I am new to Elm, probably have an incorrect understanding of the architecture and this may be an XY question (but I wouldn't know yet...)
Anyways, I am trying to create a url-routed SPA in Elm.  I am using evancz/start-app to generate individual dynamic pages using the elm-achitecture-tutorial example 1 as a starting point for each 'page':
Frontend.Pages.Home.display : Signal Html
Frontend.Pages.Home.display = StartApp.start
    { model = 0
    , update = update
    , view = view
    }

type alias Model = Int

type Action = Increment | Decrement

update : Action -> Model -> Model
update action model =
  case action of
    Increment -> model + 1
    Decrement -> model - 1

view : Signal.Address Action -> Model -> Html
view address model =
  div []
    [ button [ onClick address Decrement ] [ text "-" ]
    , div [ countStyle ] [ text (toString model) ]
    , button [ onClick address Increment ] [ text "+" ]
    ]

I am using TheSeamau5/elm-router to
route : String -> Signal Html
route = Router.match
    [ "/" :-> Frontend.Pages.Home.display
    ] Frontend.Pages.Errors.FourOhFour.display

I am using TheSeamau5/elm-history to gather the latest url:
main : Signal Html.Html
main = Frontend.Routes.route History.path

Clearly this is the error;  I am passing a Signal String into a method that takes a String.  The problem is that if I use the following:
main = Signal.map Frontend.Routes.route History.path

which I would expect Signal.map Frontend.Routes.route History.path to be of type Signal Html, instead the compiler complains of a conflict:
The type annotation for `main` does not match its definition.

7| main : Signal Html.Html
          ^^^^^^^^^^^^^^^^ As I infer the type of values flowing through your program, I see a conflict between these two types:

Html.Html

Signal Html.Html

*

*What's going on here?  It seems like Signal.Map is "unpacking" the Signal Html.  Is this the case?

It seems my core question, at any rate, is:  How can I present a single-page-app, routed to separate reactive 'pages' based on a Signal String while not reimplementing Router?
Thanks in advance.

A: I believe you are ending up with a final result of Signal (Signal Html) and main is expecting Signal Html. I believe the error you are receiving is specifically for the type it is expecting for Signal a. It is saying, I was expecting a to be Html but in fact I found it to be Signal Html.
Here are the types we have:
Signal.map : (a -> result) -> Signal a -> Signal result
Frontend.Routes.route : String -> Signal Html
Historypath : Signal String

Then we have Signal.map Frontend.Routes.route which has the type Signal String -> Signal (Signal Html).
We then apply History.path giving us the final result Signal (Signal Html)
If you change route to return Html rather than Signal Html you should be good to go.


text:
Q: Multi level json filter in angular js I am new in angular js i want to put filter in ng-repeat i have json like this
    var data = [
    {name:test1,b1:{lastValue:0},b2:{lastValue:6},b3:{lastValue:6},b4:{lastValue:0}}
    {name:test2,b1:{lastValue:6},b2:{lastValue:0},b3:{lastValue:6},b4:{lastValue:0}}
{name:test3,b1:{lastValue:6},b2:{lastValue:0},b3:{lastValue:6},b4:{lastValue:0}}
    ]

I want to put filter on lastValue i tested like this
ng-repeat = "d in data | filter:{*.lastValue:filterStatus}"

filterStatus // contain value of filter which user selected but its not working

I don't know how to do this i tried google but nothing found please help me

A: <input ng-model="filterStatus" type="text">

your filterStatus should hold model value
ng-repeat = "d in data | filter:filterStatus"

A:

var app = angular.module("Profile", []);
app.controller("ProfileCtrl", function($scope) {
  $scope.filter_val = {}
  $scope.data = [{
    name: 'test1',
    b1: {
      lastValue: 0
    },
    index: 'b1'
  }, {
    name: 'test2',
    b2: {
      lastValue: 6
    },
    index: 'b2'
  }, {
    name: 'test3',
    b3: {
      lastValue: 6
    },
    index: 'b3'
  }, {
    name: 'test4',
    b4: {
      lastValue: 0
    },
    index: 'b4'
  }, {
    name: 'test5',
    b5: {
      lastValue: 89
    },
    index: 'b5'
  }, {
    name: 'test6',
    b6: {
      lastValue: 68
    },
    index: 'b6'
  }]
  $scope.own_filter = function(val) {
    if (!$scope.filter_val.value)
      return true;
    else {
      return (String(val[val['index']]['lastValue'] || '').indexOf($scope.filter_val.value) != -1)
    }

  }
})

  <input type="text" ng-model="filter_val.value" placeholder="Enter Last Value">

{{'Name : ' + event.name}}------{{'Last Value : '+event[event['index']]['lastValue']}}

A: Use {$:filterStatus} construction:

angular.module('app', []).controller('ctrl',function($scope){
  $scope.data = [
    {name:'test1',b1:{lastValue:1},b2:{lastValue:6},b3:{lastValue:6},b4:{lastValue:0}},
    {name:'test2',b1:{lastValue:2},b2:{lastValue:0},b3:{lastValue:6},b4:{lastValue:0}},
    {name:'test3',b1:{lastValue:3},b2:{lastValue:0},b3:{lastValue:6},b4:{lastValue:0}}
  ]
})

  <input type='number' ng-model='filterStatus' ng-init='filterStatus=1'>

{{item.name}}


text:
Q: Concept on displaying cross-table(conjunction) data in ASP MVC Just a rookie in .NET MVC world and still learning
I created three EF models in framework, one is clients, one is order, and items, below is the relation:
Client          Order         Items
PK:ID          PK Order.id    PK Items.ID
...            FK:Client.id   ...
               FK:Item.id

In this case I wanna display all the client information and the item details they've bought in one table, obviously  I cannot use any DBcontext here. So what should I do to combine the three table's info and output that? Create a new model on those three?
Any ideas or article are very welcomed!

A: I would create a ViewModel with all of the Data that you want to display.  This is the model that will get populated in the controller and then it would get passed to the View.
So in the View it would use the ViewModel and wouldn't need to know about the underlying Database Model.
And in the Controller you would get the data needed and populate the ViewModel and pass that model onto the View.
Here is a page with an examples.  There are plenty more out there too.  http://sampathloku.blogspot.com/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html


text:
Q: PDO. Two SELECT, using BEGIN and COMMIT and get SQLSTATE[HY000]: General error Here is query
 BEGIN;
 SELECT NumberRenamed, ... FROM 2_1_paidused WHERE CreditAccount = ? AND ...;
 SELECT NumberRenamed, ... FROM 2_1_paidused WHERE DebitAccount = ? AND  ...;
 COMMIT;`

(... is long list with columns and conditions).
and get SQLSTATE[HY000]: General error.
Removed BEGIN; and COMMIT; and all works as expected without errors.
From my knowledge if more than one SELECT, then need to use BEGIN; and COMMIT; But appears that I am wrong. So, does it mean that it is allowed to use more than one SELECT without BEGIN; and COMMIT;? Or my query is incorrect?

A: Those are four SQL statements. You don't share any PHP code but the way you display the queries suggest that you launch them at once into a single database call. Apparently, running multiple queries in PDO is quite tricky—no idea if you got it right.
In any case, your transaction code is redundant:

*

*PDO has builtin functions to start and commit transactions. There's no need to run commands manually.

*You don't write into the database, thus transactions don't have any purpose anyway.

I'm pretty sure you just need to run your two SELECT queries separately.

Edit: perhaps you're confused with BEGIN ... END. That's an entirely different feature. In MySQL, you can only use it in the body of stored routines.


text:
Q: How to add more than one delimiter in Bash I'm trying to figure out how to set two delimiters: one is newline and another one is space so when I read numbers from file that is filled like this
1 2 3
4
5
6

I get one number by order like 1,2,3,4,5,6. I'm using read command to read numbers. Thanks!

A: Your question is pretty unclear but based on the sample and expected output the trivial solution would be to use tr:
$ cat file | tr '[ \n]' ,
1,2,3,4,5,,6,

but there is a space after 5 so you need to use -s to squeeze the repeats:
$ cat file | tr -s '[ \n]' ,
1,2,3,4,5,6,

which still leaves you with a nasty trailing comma and a missing newline from the end. That can be handled with sed or awk. (with Sapphire and Steel narrator's voice) Awk has been assigned:
$ cat file | tr -s '[ \n]' , | awk 'sub(/,$/,"")' # fails if output is just 0
1,2,3,4,5,6                                       # add ||1 or ||$0!="" to fix

Wait. Since we started awk why bother with the tr at all:
$ awk '{
    gsub(/ +/,",",p)            # replace space runs with a single comma
    printf "%s",p
    p=(p~/,$/||NR==1?"":",") $0 # 5 followed by space leaves a comma in the end so...
}
END {
    print p
}' file
1,2,3,4,5,6

Well that turned out looking complicated and I just now noticed you did mention using the read command so maybe I'm way off with my solutions and I should've used bash scripting from the beginning:
s=""                     # using this neat trick I just learned here ;D
while read line          # read a full line
do
    for word in $line    # read word by word
    do
        echo -n $s$word  # output separator and the word
        s=,              # now set the separator
    done
done < file
echo                     # newline to follow
1,2,3,4,5,6

Yes, it is Saturday evening and I have no life.


text:
Q: Legitimate uses for HTTP 502 The spec declares
502 Bad Gateway
The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.
Suppose I have a "frontend" server that serves HTML pages. This frontend server makes REST calls to an API server that returns JSON. Like this:
+--------+              +----------+    +-----+
|        | start req -> |          | -> |     |
| client |              | frontend |    | api |
|        | get resp <-  |          | <- |     |
+--------+              +----------+    +-----+

If the API server returns a 5xx back to the frontend server, would 502 be an appropriate response to return to the client, or would 500 be more appropriate?

A: If you own both the frontend and API servers, and the distinction between them is invisible to the client, then they are working as a single unit, and you shouldn't use the proxy response codes. If the API server returns any 5xx code, it's best for the frontend server to return 500, meaning "my system encountered an error".
If on the other hand the API server is someone else's e.g. Facebook and you're expecting the client to know that you're proxying a request to Facebook, it might be appropriate to echo Facebook's response codes. However, normally it would be best to use 500 even if Facebook returns 502, because a 502 from them means one of their downstream servers failed, but your request to Facebook was otherwise successful.


text:
Q: Grunt Modernizr doesn't add css classes Hello I want to use Grunt Modernizr. It works in my javascript. But the script doesn't add Css Classes? Does anybody know why?
modernizr: {
        prod: {
            parseFiles: true,
            customTests: [],
            devFile: false,
            dest: '<%= path.jsSrc %>build/modernizr.min.js',
            tests: [
                "input",
                "inputtypes",
                "touchevents",
                "css/flexbox",
                "css/flexboxlegacy",
                "css/flexboxtweener"
            ],
            extensibility: [
                "domPrefixes",
                "prefixes",
                "mq",
                "testAllProps",
                "testProp",
                "testStyles",
                "html5shiv",
                "setClasses"
            ],
            extra: {
                "mq" : false,
                "cssclasses" : true
            },
            files: {
                src: [
                    '<%= path.cssSrc %>**/*.scss',
                    '<%= path.jsSrc %>*.js',
                    '<%= path.jsSrc %>libs/*.js'
                ]
            },
            uglify: true
        }
    },

I don't see no-flexbox for example on my html

A: I had the same problem and I replaced "extensibility" with "options", so try this:
options: [
    "domPrefixes",
    "prefixes",
    "mq",
    "testAllProps",
    "testProp",
    "testStyles",
    "html5shiv",
    "setClasses"
]

Check out the customizr readme :
https://github.com/doctyper/customizr


text:
Q: Version conflict while adding Google Cloud Storage support to existing Webapp I have a webapp & a java application that connects to Bigquery. I'm trying to add support for Cloud Storage using the StorageSample example.
But when running this code:
Storage storage = new Storage.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
    BigqueryUtils.PROJECT_ID).build();

I get the following error:
You are currently running with version 1.17.0-rc of google-api-client. You need version 1.14.1-beta of google-api-client to run version 1.14.1-beta of the Cloud Storage API library.

A: Quick fix: Hi Febian: Why don't you just grab a new version of the client lib from here?
Better way to manage libs: I have had best luck using Maven to manage dependencies for Google Java Client Libs. Check out the "Add Library to Your Project" link on the same page.


text:
Q: How do I create a 'for' loop in Smarty 2? I would like to know if it is possible to do something similar to a for cycle using Smarty 2.
I would like to have something like this:
<select>
{for $i from 1950 to 2000 }
   <option value="{$i}">{$i}</option>
{/for}
</select>

What function should I use, if any?

A: Try {section} as it is described in the smarty docs
By the way: Check the {html_options} function: html_options docs

A: You could use PHP's range function:
<select>
    {foreach item=i from=1950|@range:2000}
        <option value="{$i}">{$i}</option>
    {/foreach}
</select>

A: This is an old question and already has an accepted answer, but the answer was basically just a link.  I have posted this as a more complete answer, to avoid future visitors having to trawl the docs to find the relevant example.

In Smarty 2, loops are achieved using the {section} tag, which covers quite a broad range of use-cases.  To write the equivalent of a PHP for() loop, the following syntax is used:
<select>
{section name="i" start=1950 loop=2001}
   <option value="{$smarty.section.i.index}">{$smarty.section.i.index}</option>
{/section}
</select>

Note that the loop property refers to the number at which Smarty will break out of the loop, so it needs to be 1 higher than the final number you want to iterate over.

ADDENDUM:
Although this is not directly relevant to the question (which is about Smarty 2), it is worth noting that Smarty 3 introduced a {for} tag, so you can now do the following, which is a lot simpler:
<select>
{for $i=1950 to 2000}
   <option value="{$i}">{$i}</option>
{/for}
</select>


text:
Q: Error compiling Aruco on Mac OS X: Undefined symbols for architecture x86_64: I am trying to compile Aruco using their short example. I am using Mac OS X (10.13.2), the compiler is clang (900.0.39.2), opencv (3.4.1_2 installed via brew) and Aruco (3.0.4).
The simple example is:
#include <iostream>
#include <aruco/aruco.h>
#include <opencv2/highgui.hpp>
int main(int argc,char **argv)
{
  try
  {
      if (argc!=2) throw std::runtime_error("Usage: inimage");
      aruco::MarkerDetector MDetector;
      //read the input image
      cv::Mat InImage=cv::imread(argv[1]);
    //Ok, let's detect
      MDetector.setDictionary("ARUCO_MIP_36h12");
      //detect markers and for each one, draw info and its boundaries in the image
      for(auto m:MDetector.detect(InImage)){
          std::cout<<m<<std::endl;
          m.draw(InImage);
      }
      cv::imshow("in",InImage);
      cv::waitKey(0);//wait for key to be pressed
  } catch (std::exception &ex)
  {
      std::cout<<"Exception :"<<ex.what()<<std::endl;
  }
}

My CMakeLists.txt is:
cmake_minimum_required(VERSION 2.8)
project(aruco_testproject)
SET(CMAKE_CXX_FLAGS "-std=c++11")
find_package(aruco REQUIRED )
add_executable(aruco_simple aruco_simple.cpp)
target_link_libraries(aruco_simple  aruco)

And the error I get when running make (after running cmake with no issues) is:
Scanning dependencies of target aruco_simple
[ 50%] Building CXX object CMakeFiles/aruco_simple.dir/aruco_simple.cpp.o
[100%] Linking CXX executable aruco_simple
Undefined symbols for architecture x86_64:
  "cv::imread(cv::String const&, int)", referenced from:
      _main in aruco_simple.cpp.o
  "cv::imshow(cv::String const&, cv::_InputArray const&)", referenced from:
      _main in aruco_simple.cpp.o
  "cv::waitKey(int)", referenced from:
      _main in aruco_simple.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [aruco_simple] Error 1
make[1]: *** [CMakeFiles/aruco_simple.dir/all] Error 2
make: *** [all] Error 2

I am fairly new to compiling (as maybe obvious!)

A: The last line of my makefile need to be
target_link_libraries(aruco_simple  aruco ${OpenCV_LIBS})


text:
Q: How do I do indexOf for arrays with optionals? In Swift2, how can you do indexOf on arrays that contain optionals? The following example won't compile:
var strings: [String?] = ["hello", nil, "world"]
let index = strings.indexOf("world")

with the compiler complaining
"Cannot invoke indexOf with an argument list of type '(String)'"
A naive approach without indexOf would be:
let index: Int = {
    for var i = 0; i < strings.count; i++ {
        let s: String? = strings[i]
        if s == "world" {
            return i
        }
    }
    return -1
}()

Isn't there any way to use the built-in indexOf function?
The same example however works for arrays with non-optionals:
var strings: [String] = ["hello", "world"]
let index = str.indexOf("world")

A: Or even simpler:
let strings: [String?] = ["hello", nil, "world"]
strings.indexOf{ $0 == "world" }

This works because == is defined for optionals as well

A: You can use an expression in "trailing closure" for indexOf:
var arr: [String?] = ["hello", nil, "world"]
let i = arr.indexOf() { $0 != nil && $0 == "world" }


text: Q: how to update bitmap? I am trying to read the angle from electronic compass which connected to an Arduino, the Arduino sends the angle to c#, in c#, I uplaode google map (gMap.net) and put compass image as Bitmap, this bitmap rotates acoording to the angle recieved. I created timer to read from the port repeatlly. the prblem is when the bitmap update its angle, it is flashing because it is deleted and come up agian whith new position.if I decrease the delay of the timer, I can not use other buttons because the program stuck in the loop of the timer. how can I prvent this flashing.